Use case for method, System.identityHashCode (Object x)
I have read the javadoc of this JAVA API method, System.identityHashCode(Object x)
and have not been able to understand the typical use case for this method. Classes that require it hashCode()
are recommended to have an overridden method hashCode()
, so what is the purpose of this method if the object class already has a default hashCode()
?
source to share
Suppose class C extends class B and class B overrides hashCode
and equals
.
Now, suppose for class C you want to use the standard implementation hashCode
and equals
that implemented in the class Object
. You usually don't want to do this, but assume that each instance of the class C
must 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 overrides toString
and you want C toString to have a standard Object class implementation, you can write in C:
@Override
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(this));
}
source to share
There are many use cases. This is primarily useful if for some reason you have a collection of objects and only care about their object IDs. This is really rare. One example is IdentityHashMap (like @Boris says). It would actually be easy to use hashCode
for objects for such a hashmap, but using the hash identity would theoretically be faster because it can avoid "collisions" between objects that are logically equal
not the same object (this also avoids poorly implemented hash functions I think).
There are not many use cases in such collections either. You can see examples of using IdentityHashMap here: Practical Using IdentityHashMap in Java 6
source to share
Just one difference, if the given object is null , this method gives 0 .
Example 1:
obj.hasCode ();
This code throws a nullPointerException if obj is null.
Example 2:
System.identityHashCode (OBJ);
This method returns 0 and does not throw an exception because it checks for null. Also it gives HashCode that the default hashCode method would return even if you override it
Did this answer help you?
source to share