views:

95

answers:

4

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.

+3  A: 

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

Frostman
MultiSet looks pretty useful - can't count how many times I've written code to build a Map<SomeType, Integer> to count the number of occurrences of objects in another type of Collection. +1 for increasing my knowledge
matt b
+2  A: 

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.

matt b
+1  A: 

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.

matsev
A: 

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.

Steve Kuo