user1464139
user1464139

Reputation:

What interface in Java can I use to store unique objects?

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

Answers (5)

Ahmad
Ahmad

Reputation: 2190

Well, you should Set collections like HashSet. Do remeber following points.

  1. Don't forget to implement equals method in classes whose objects your Set will contain.

  2. 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

Abhishek
Abhishek

Reputation: 2253

use set interface for storing unique object ....

Upvotes: 0

Brian Agnew
Brian Agnew

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

Adam Sznajder
Adam Sznajder

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

Jigar Joshi
Jigar Joshi

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

Related Questions