我可以拥有一组包含相同元素的集合吗?

发布于 2024-08-26 20:32:10 字数 122 浏览 5 评论 0原文

我用一套很方便。我喜欢如何向集合“添加”(“删除”)元素。检查给定元素是否在集合中也很方便。

唯一的问题是,我发现如果集合已经有这样的元素,我无法将新元素添加到集合中。是否有可能拥有可以包含多个相同元素的“集合”。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

べ映画 2024-09-02 20:32:10

您必须使用 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

野味少女 2024-09-02 20:32:10

如果您想要重复项,Set 可能不是您的最佳集合选择。集合,根据定义,不允许重复:

不包含重复元素的集合。更正式地说,集合不包含满足 e1.equals(e2) 的一对元素 e1 和 e2,并且最多包含一个 null 元素。正如其名称所暗示的,该接口对数学集合抽象进行建模。

除非您有一个真正需要使用 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:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

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.

魔法唧唧 2024-09-02 20:32:10

如果元素相同,则无需多次存储它们。如果您想跟踪每个元素有多少个实例,最好使用 地图

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.

深海蓝天 2024-09-02 20:32:10

根据定义,Set 不能有重复的元素。 “重复”由元素的相等性定义(请参阅其 equalshashCode 方法)。如果您想要重复项,请使用允许重复项的Collection,例如ArrayList

A Set by definition cannot have duplicate elements. "Duplicate" is defined by the element's equality (see its equals and hashCode methods). If you want duplicates, the use a Collection that allows duplicates, such as ArrayList.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文