开发者

Can I have a set containing identical elements?

开发者 https://www.devze.com 2022-12-24 04:40 出处:网络
It is convenient for me to use a set. I like how I can \"add\" (\"remove\") an element to (from) t开发者_开发知识库he set. It is also convenient to check if a given element is in the set.

It is convenient for me to use a set. I like how I can "add" ("remove") an element to (from) t开发者_开发知识库he 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.


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号