1

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 :-(

5 Answers5

7

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 
jmj
  • 237,923
  • 42
  • 401
  • 438
2

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

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.

Ahmad
  • 2,110
  • 5
  • 26
  • 36
0

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.

Adam Sznajder
  • 9,108
  • 4
  • 39
  • 60
0

use set interface for storing unique object ....

Abhishek
  • 2,255
  • 1
  • 13
  • 21