Java hashcode based on identity

hashcode, identity, java

Solution

System.identityHashCode(Object) provides this behaviour.

You would write this:

class B extends A {
  public int hashCode() {
    return System.identityHashCode(this);
  }
}

Please check the equals-method, that it only returns true, if the two objects are the same. Otherwise it would break behaviour described for equals and hashCode. (To be correct, the equals-method has to return false, if you get different hashcodes for two objects.) To provide an implementation of equals() that comply with the given hashCode()-method:

public boolean equals(Object other){
   return this == other;
}

Problem

The default behavior of Object.hashCode() is to return essentially the "address" of the object so that a.hashCode() == b.hashCode() if and only if a == b. How can I get this behavior in a user-defined class if a superclass already defines hashCode()? For instance: ``` class A { public int hashCode() { return 0; } } class B extends A { public int hashCode() { // Now I want to return a unique hashcode for each object. // In pythonic terms, it'd look something like: return Object.hashCode(this); } } ``` Ideas?

Original source