我可以拥有一组包含相同元素的集合吗?
我用一套很方便。我喜欢如何向集合“添加”(“删除”)元素。检查给定元素是否在集合中也很方便。
唯一的问题是,我发现如果集合已经有这样的元素,我无法将新元素添加到集合中。是否有可能拥有可以包含多个相同元素的“集合”。
It is convenient for me to use a set. I like how I can "add" ("remove") an element to (from) the set. It is also convenient to check if a given element is in the set.
The only problem, I found out that I cannot add a new element to a set if the set has already such an element. Is it possible to have "sets" which can contain several identical elements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须使用 MultiSet 或 HashMap,在其中保存元素数量。
ps 使用哈希图,您仍在使用 O(log n) 操作进行添加/删除
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html
You must use MultiSet or HashMap, where you save count of elements.
p.s. with hashmap you still doing add/remove with O(log n) operations
http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html
如果您想要重复项,Set 可能不是您的最佳集合选择。集合,根据定义,不允许重复:
除非您有一个真正需要使用 Set 的复杂用例(在这种情况下您可以使用上面 @Frostman 描述的 MultiSet),否则您最好只使用 列表。
A Set might not be the best choice of collections for you if you want duplicates. Sets, by definition, do not allow duplicates:
Unless you have a complex use case that really requires using a Set (in which case you can use a MultiSet as @Frostman describes above), you might be better off just using a List.
如果元素相同,则无需多次存储它们。如果您想跟踪每个元素有多少个实例,最好使用 地图。
There is no need to store the elements several times if they are identical. If you would like to keep track of how many instances of each element you have, you'd better use a Map.
根据定义,
Set
不能有重复的元素。 “重复”由元素的相等性定义(请参阅其equals
和hashCode
方法)。如果您想要重复项,请使用允许重复项的Collection
,例如ArrayList
。A
Set
by definition cannot have duplicate elements. "Duplicate" is defined by the element's equality (see itsequals
andhashCode
methods). If you want duplicates, the use aCollection
that allows duplicates, such asArrayList
.