HashMap does not call Object.equals?

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

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

I tried passing a new identical object to the equals method and returns true, so the problem is not in my comparison code.

From what I compiled using debugging, the equals (Object) method in my object is never called.

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

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

+3
source share
2 answers

You also need to override Object.hashcode(). Take a look at the link as it indicates that hashcode()both equals()have a contract to provide the correct functionality in HashTable, HashMapand HashSet.

The HashMapvalues ​​are stored in buckets, which are reached by the key hash. Once a suitable bucket is found, the equals method is 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 is good.

+10

hashCode, , HashMap ( ) , . Java " " - , hashCode .

+1

Source: https://habr.com/ru/post/1546772/


All Articles