24

我不明白为什么 JCF(Java 集合框架)没有Bag实现(允许重复而不维护顺序)。 Bag性能将比 JCF 中当前的 Collection 实现好得多。

  • 我知道如何Bag用 Java 实现。
  • 我知道Bag在 Apache commons 中可用。
  • 我知道还有其他实现可以用作 aBag但是与 a 相比,在其他实现中还有很多工作要做Bag

为什么 Java Collections 框架没有提供这样的直接实现?

4

3 回答 3

15

发表我的评论作为答案,因为它最好地回答了这个问题。

这里提交的错误报告:

Collection 框架的维护者对设计和实现这些接口/类的热情并不高。我个人不记得需要一个。在 JDK 之外开发的流行包在现实世界中证明其价值后,更有可能将其导入 JDK。

对 Bags 的支持需求在今天仍然有效。

番石榴支持它。还有GS-Collections

于 2013-03-25T14:39:44.467 回答
3

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

于 2014-07-01T09:03:10.983 回答
0

JDK 尝试为您提供通用数据结构的实现,并允许您在通用结构无法满足您的目的时实现任何东西。他们可能认为这不是常见的数据结构。从实用性来看,他们不可能实现每个数据结构或满足每个人的要求。你认为常见的东西可能对大多数人来说并不常见。

于 2013-03-25T06:45:07.243 回答