Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map Implementation not based on HashCode

Tags:

java

Is there some implementation of java.util.Map that does not uses HashCode?

I have the following problem:

  1. I store an object associated to another object on a HashMap;
  2. Change a property from the key object used on step 1;
  3. As the hashcode is used to store the keys on the regular implementation of HashMap, when I perform a get() on the HashMap, I get null, because the old object hashCode was different at step 1.

Is there a solution for that? Or should I really use just immutable fields for my equals / hashCode methods?

like image 469
Francisco Spaeth Avatar asked Feb 04 '12 14:02

Francisco Spaeth


People also ask

Does HashMap use hashCode?

HashMap uses hashCode() and equals() methods on keys for the get and put operations. So HashMap key objects should provide a good implementation of these methods.

Does HashMap use hashCode or equals?

In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.

What happens if we do not override hashCode () and equals () in HashMap?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

How do you avoid a hash collision in Java?

The only way to avoid (or rather minimize) collisions is to create a hash function that creates the best possible distribution of values throughout the HashMap. Depending on the density of your HashMap and the quality of your hash code , collisions are almost inevitable, hence the need to override the two methods.


1 Answers

IdentityHashMap uses the Object identity instead of the hashCode; however that does mean that you require the original object used as key to retrieve the value of the map. Other options would be redefine the hashcode to exclude the mutable parts of the object, or - if you can't redefine the hashCode for some reason - wrap the object in another object which provides a stable hashCode.

like image 170
Mark Rotteveel Avatar answered Sep 24 '22 18:09

Mark Rotteveel