Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case for method , System.identityHashCode(Object x)

Tags:

java

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()?

like image 542
Sabir Khan Avatar asked Apr 19 '26 02:04

Sabir Khan


1 Answers

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));
}
like image 95
Eran Avatar answered Apr 23 '26 08:04

Eran