Week 58 — What is the "identity hash code" and how does it differ from other `hashCode()`s?
Question of the Week #58
What is the "identity hash code" and how does it differ from other
hashCode()
s?2 Replies
The class
Object
provides a method called hashCode()
which returns an int
which should return an int
that:
- Is the same for two equal objects, i.e. if a.equals(b)
, then a.hashCode()
should return the same result as b.hashCode()
- ideally be different for most different objects. In case a.equals(b)
returns false
, then a.hashCode()
and b.hashCode()
should likely be different.
This method is used by data structures that require hashing like HashMap
/HashSet
.
If this method is not overridden, its hashCode
returns the "identity hash code" of the object.
When an object is created and its identity hash code is requested, the JVM will generate a random number and save it into the object. When it is requested again, the same int
will be returned.
Two different objects with the same data may have different identity hash codes.
The method System.identityHashCode(Object)
always returns the identity hash code of the object passed as a parameter, even if the hashCode()
. method is overridden.
📖 Sample answer from dan1st
The identity hash code in Java is provided by theSystem.identityHashCode(Object obj)
method. It returns the same hash code for the given object, regardless of itshashCode()
implementation. ThehashCode()
method is typically overridden by classes to generate hash codes based on the object's contents, but the identity hash code is solely based on the object's memory address.
Submission from ig.imanish