I can't figure out why JCF (Java Collection Framework) does't have a Bag
implementation(to allow duplicates and not maintain order). Bag
performance would be much better than current Collection implementations in JCF.
Bag
in Java.Bag
is available in Apache commons.Bag
but there is so much work to do in other implementations compared to a Bag
.Why has the Java Collections framework not provided direct implementations like this?
The Collection interface is the root interface of the Java collections framework. There is no direct implementation of this interface. However, it is implemented through its subinterfaces like List , Set , and Queue .
The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. For Example, the HashSet class implements the Set interface which is a subinterface of the Collection interface.
Map interface does not implement the Collection interface. It can only contain a unique key but can have duplicate elements.
java implements a generic bag using a linked list. The implementation is the same as Stack.
Posting my comment as an answer since it answers this question best.
From the bug report filed here :
There isn't a lot of enthusiasm among the maintainers of the Collection framework to design and implement these interfaces/classes. I personally can't recall having needed one. It would be more likely that a popular package developed outside the JDK would be imported into the JDK after having proved its worth in the real world.
The need for having support for Bags is valid today.
Guava has support for it. Also GS-Collections.
Currently, bag violates the collections contract. Many methods are in conflict with the current collections rules.
"Bag is a Collection that counts the number of times an object appears in the collection. Suppose you have a Bag that contains {a, a, b, c}
. Calling getCount(Object)
on a
would return 2, while calling uniqueSet()
would return {a, b, c}
.
Note that this interface violates the Collection contract. The behavior specified in many of these methods is not the same as the behavior specified by Collection. The noncompliant methods are clearly marked with "(Violation)" in their summary line. A future version of this class will specify the same behavior as Collection, which unfortunately will break backwards compatibility with this version."
boolean add(java.lang.Object o) (Violation) Add the given object to the bag and keep a count. boolean removeAll(java.util.Collection c) (Violation) Remove all elements represented in the given collection, respecting cardinality.
Please see the link for more information: HERE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With