JavaDeveloper
JavaDeveloper

Reputation: 5660

How to use Hashset for non-string objects in java

Lets say I have created a class called Time whose constructor takes 3 params. hour, mins and secs. Now, I create an object t1 = new Time(10, 10, 10); and then another object t2 = new Time(10, 10, 10)

now I use them in hashset.

hashset.add(t1);
hashset.add(t2);

Now size of hashset would be 2. How to modify this to be of size 1 if the values of the objects is the same ?

example:

void eradicateDuplicate(List<Time> list) {

  for (Time t : list) {
     hashSet.add(t);
   } 

}

I want this code to eradicate all duplicate time objects with the same value ?

Thanks,

Upvotes: 0

Views: 96

Answers (2)

MTilsted
MTilsted

Reputation: 5543

This will happen automatically IF you implement the methods #hashCode and #equals in your Time object.

Upvotes: 5

tbodt
tbodt

Reputation: 17007

You don't need to do anything. The second will not be added if it is the same as the first.

Upvotes: 0

Related Questions