2

This example makes it look easy:

HashSet<Integer> hSet = new HashSet<Integer>();

hSet.add(new Integer("1"));
hSet.add(new Integer("2"));
hSet.add(new Integer("3"));

System.out.println(hSet.contains(new Integer("3")));

true

But when I use it on a Movie object (which I want to check):

Set<Movie> hSet = new HashSet<Movie>();

hSet.add(new Movie(222, "Lord of the Rings", "something"));
System.out.println(hSet);

System.out.println(hSet.contains(new Movie(222, "Lord of the Rings", "something")));

false

The hSet print shows:

[id: 222name: Lord of the Rings]

I don't see a difference in adding a new Integer or adding a new movie object to the list. So why isn't my example working?

//edit.

If anyone is looking for a good reference, this helped me out.

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185

1 Answers1

2

You need to override the hashcode and equals method in Movie class.

In hashset whenever we add the objects, before adding the object it will check the hashcode value of an object by overridding the hashcode If the calculated hashcode value is already available in the set, then it will call equals method and check the object which we are going to add is equal with the already available object in set. If the object is equal then it will not add it into the set or else it will add the object into the set.

Vishnu T S
  • 3,476
  • 2
  • 23
  • 39