Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap Not Calling Object.equals?

I wrote a class that overrides the equals(Object) method in class Object to compare objects of the class type to other objects of a class type using the object's instance values.

When I put an instance of the object in a HashMap as the key, and then call get(Object) on the map with a new but identical object as the key, it returns null.

I've tried passing a new, identical object to the equals method and it returns true, so the problem isn't my comparison code.

From what I've gathered through debugging, the equals(Object) method in my object is never called.

But if you use a String key in a HashMap and then pass a new instance with identical characters to get(Object), it returns the value successfully.

Why is this happening? What do I have to do to have HashMap test keys based on MY equals method?

like image 405
bgroenks Avatar asked Dec 15 '22 23:12

bgroenks


1 Answers

You need to also override Object.hashcode(). Take a look at the link, as it specifies that hashcode() and equals() have a contract to ensure proper functionality in HashTable's, HashMap's, and HashSet's.

In a HashMap, values are stored in buckets, which are reached by the hashcode of the key. Once the proper bucket is found, the equals method is then applied to each member of the bucket until equality is determined. Because of this, it is important to make sure that your hash algorithm 'hashes well'.

like image 166
nicholas.hauschild Avatar answered Dec 30 '22 12:12

nicholas.hauschild