You are here: Home ยป Retrieving original hashcode of a Java object

Retrieving original hashcode of a Java object

Posted on Sunday, March 09 2014 at 21:33 (Age: 5 yrs) | Category: Software Engineering, Java

For debugging Java applications, it is sometimes useful to know if two references point to the same or to different objects - this can be easily checked by evaluating the return value of hashCode() (the default implementation from java.lang.Object returns distinct integers for distinct objects). However, this might not work if hashCode() is overridden - in that case, hashCode() might return the same value for different objects to fulfill the equals() contract. In that case, it is still possible to retrieve the same hashCode() value as it would be returned by java.lang.Object if the hashCode() method was not overridden, by using System.identityHashCode() on this object:

public class Value {
    private int theValue;

    public Value(int val) {
        theValue = val;
    }

    @Override
    public int hashCode() {
        return theValue;
    }
	
    public static void main(String[] args) {
        Value value = new Value(42);
        System.err.println(value.hashCode());
        System.err.println(System.identityHashCode(value));
    }
}
Output:
42
1024180077

No comments

Be the first to post a comment!