Sabir Khan
Sabir Khan

Reputation: 10142

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

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

Upvotes: 3

Views: 199

Answers (3)

Enno Shioji
Enno Shioji

Reputation: 26882

There aren't a lot of use cases. It's primarily useful if for some reason you have a collection of objects, and only care about their object identities. This is really rare. One example is IdentityHashMap (like @Boris says). It would actually be fine to just use hashCode of the objects for such hash map, but using identity hash would theoretically be faster, because it can avoid "collisions" between objects that are logically equal but aren't the same object (it also allows avoiding of badly implemented hash functions, I guess).

There aren't a lot of use case for such collections, either. You can see use cases for IdentityHashMap here: Practical use of IdentityHashMap in Java 6

Upvotes: 1

Eran
Eran

Reputation: 394126

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));
}

Upvotes: 7

Oscar Vicente Perez
Oscar Vicente Perez

Reputation: 857

Just one difference, if the Object given is null this Method gives 0.

Example 1:

obj.hasCode();

This code throws nullPointerException if the obj is null.

Example 2:

System.identityHashCode(obj);

This method return 0 and doesn't throw an exception cause it checks for null. Also it gives the HashCode that the default hashCode method would return even if you overrides it

Did this answer help you?

Upvotes: -1

Related Questions