问题
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.
- I know how to implement Bag in java.
- I know there is a Bag collection in Apache common.
- I know i can use any implementation as a bag! but there are so much work in other implementations compare to Bag.
Why has the Java Collections framework not provided direct implementations like this?
回答1:
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.
回答2:
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
回答3:
JDK tries to give you implementation of common data structures and allow you to implement anything if common structures won't server your purpose. They may have thought that it is not common data structure.From practicality, it is not possible for them to implement every data structure out there or satisfy everybody's requirements. What you think common may not be common for majority.
来源:https://stackoverflow.com/questions/15608667/why-is-there-no-direct-implemention-of-bag-in-java-collection-framework