0

Consider the following code:

public class MyClass {

    public static void main(String[] args) {
        Object obj = new Object();
        System.out.println(obj.hashCode());
        System.out.println(System.identityHashCode(obj));
        }
}

Output:

328332828
328332828

Then what is the use of using hashCode() and identityHashCode()?

2 Answers 2

2

JavaDoc of identityHashCode() Says:

Returns an integer hash code for the parameter. The hash code returned is the same one that would be returned by the method java.lang.Object.hashCode(), whether or not the object's class has overridden hashCode(). The hash code for null is 0.

To put it simply:

If you have overridden hashCode() method in your class, then calling identityHashCode() will invoke default hashCode() method, not your overridden method.

Sign up to request clarification or add additional context in comments.

Comments

1
  • hashCode is overrideable
  • identityHashCode is default (not overrided) function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.