Reputation:
I need to create a class that will store a unique object elements. I don't need to sort these elements but they must be unique.
Can someone give me advice as to what interface I should be using? It was suggested to me by one person that I could use Set and then another person said Vector or List. Now I am totally confused :-(
Upvotes: 1
Views: 6189
Reputation: 2190
Well, you should Set collections like HashSet. Do remeber following points.
Don't forget to implement equals method in classes whose objects your Set will contain.
Also, implement hashcode method with a good algo, that equally devides your collection in buckets. you can do it by possibly taking into account a particular property of object that you consider in equals method.
Upvotes: 1
Reputation: 272217
From the doc for Set:
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.
(my emphasis)
Note that these objects should not be mutable as to affect their equality. Otherwise you could insert an object, then change it such that it would equal()
another object in the set. I wouldn't expect a Set
object to enforce uniqueness retrospectively.
Upvotes: 2
Reputation: 9206
You have to use Set
. It was designed to store unique objects. More formally, sets contain no pair of elements e1
and e2
such that e1.equals(e2)
, and at most one null element. This is why you have to remember to implement equals
method in class which objects will be stored in a collection.
Upvotes: 0
Reputation: 240860
Set
is what exactly you are looking for
Set<Integer> uniqueValues = new HashSet<Integer>();
uniqueValues.add(1);
uniqueValues.add(2);
uniqueValues.add(3);
uniqueValues.add(2);// will be ignored
Upvotes: 7