Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding contains method of Java HashSet

Newbie question about java HashSet

Set<User> s = new HashSet<User>();
User u = new User();
u.setName("name1");
s.add(u);
u.setName("name3");
System.out.println(s.contains(u));

Can someone explain why this code output false ? Moreover this code does not even call equals method of User. But according to the sources of HashSet and HashMap it have to call it. Method equals of User simply calls equals on user's name. Method hashCode return hashCode of user's name

like image 715
user12384512 Avatar asked Aug 11 '11 13:08

user12384512


People also ask

How does contains method work in HashSet?

The contains() method of Java HashSet class is used to check if this HashSet contains the specified element or not. It returns true if element is found otherwise, returns false.

How do you check an element in a HashSet?

To check whether an element is in a HashSet or not in Java, use the contains() method.

Does HashSet have get method?

HashSet does not have a get method to retrieve elements. HashSet implements the Set interface. The Set is a collection with no duplicates. This interface models the mathematical set abstraction.


2 Answers

If the hash code method is based on the name field, and you then change it after adding the object, then the second contains check will use the new hash value, and won't find the object you were looking for. This is because HashSets first search by hash code, so they won't bother calling equals if that search fails.

The only way this would work is if you hadn't overridden equals (and so the default reference equality was used) and you got lucky and the hash codes of the two objects were equal. But this is a really unlikely scenario, and you shouldn't rely on it.

In general, you should never update an object after you have added it to a HashSet if that change will also change its hashcode.

like image 144
dlev Avatar answered Sep 24 '22 10:09

dlev


Since your new User has a different hashcode, the HashSet knows that it isn't equal.

HashSets store their items according to their hashcodes.
The HashSet will only call equals if it finds an item with the same hashcode, to make sure that the two items are actually equal (as opposed to a hash collision)

like image 41
SLaks Avatar answered Sep 23 '22 10:09

SLaks