0

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,

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

2 Answers2

5

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

Philippe Marschall
  • 4,452
  • 1
  • 34
  • 52
MTilsted
  • 5,425
  • 9
  • 44
  • 76
0

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

tbodt
  • 16,609
  • 6
  • 58
  • 83