Source of Bag.java


  1: import java.util.Collection;

  3: /**
  4:  * @param <T> the base type of this Bag
  5:  * @author Mark Young (A00000000)
  6:  */
  7: public interface Bag<T> extends Collection<T> {

  9:     /**
 10:      * Remove an item from this Bag. The item to remove is at the discretion of
 11:      * the implementation.
 12:      *
 13:      * @return an arbitrary item removed from this Bag
 14:      */
 15:     public T remove();

 17:     /**
 18:      * Count how many times the given item appears in this Bag. That is, count
 19:      * each {@code e} such that {@code Objects.equals(anItem, e)}.
 20:      *
 21:      * @param anItem the item to count
 22:      * @return how many times that item appears in this Bag
 23:      */
 24:     public int getFrequency(T anItem);
 25:     
 26:     /*
 27:      * Some default implementations for methods. I don't know why Collection
 28:      * doesn't give these itself!
 29:      */
 30:     
 31:     @Override
 32:     public default boolean addAll(Collection<? extends T> c) {
 33:         int oldSize = size();
 34:         for (var item : c) {
 35:             add(item);
 36:         }
 37:         return oldSize != size();
 38:     }
 39:     
 40:     @Override
 41:     public default void clear() {
 42:         while (!isEmpty()) {
 43:             remove();
 44:         }
 45:     }
 46:     
 47:     @Override
 48:     public default boolean containsAll(Collection<?> c) {
 49:         for (var obj : c) {
 50:             if (!contains(obj)) {
 51:                 return false;
 52:             }
 53:         }
 54:         return true;
 55:     }
 56:     
 57:     @Override
 58:     public default boolean isEmpty() {
 59:         return size() == 0;
 60:     }
 61:     
 62:     @Override
 63:     public default boolean removeAll(Collection<?> c) {
 64:         int oldSize = size();
 65:         for (var obj : c) {
 66:             remove(obj);
 67:         }
 68:         return oldSize != size();
 69:     }
 70:     
 71:     @Override
 72:     public default boolean retainAll(Collection<?> c) {
 73:         int oldSize = size();
 74:         for (Object obj : toArray()) {
 75:             if (!c.contains(obj)) {
 76:                 remove(obj);
 77:             }
 78:         }
 79:         return oldSize != size();
 80:     }

 82: }