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