I read javadoc of this JAVA API method, System.identityHashCode(Object x) and not able to understand a typical use case of this method. Classes that need hashCode() are recommended to have overridden hashCode() method of their own so what is the purpose of this method if Object class already has default hashCode()?
Suppose that class C extends class B and class B overrides hashCode and equals.
Now suppose that for class C, you wish to use the default implementation of hashCode and equals as implemented in the Object class. Normally you don't want to do that, but suppose that each instance of the C class should be a unique key in some HashMap.
You can write :
public class C extends B
{
@Override
public int hashCode ()
{
return System.identityHashCode(this);
}
@Override
public boolean equals (Object other)
{
return this == other;
}
}
Similarly, if B override's toString and you want C's toString to have the default implementation of the Object class, you can write in C :
@Override
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(this));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With