Object.hashCode() 的默认行为本质上是返回对象的“地址”,以便 a.hashCode() == b.hashCode() 当且仅当 a == b 时。如果父类(super class)已经定义了 hashCode(),我如何在用户定义的类中获得此行为?例如:
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);
}
}
想法?
最佳答案
System.identityHashCode(Object)提供这种行为。
你会这样写:
class B extends A {
public int hashCode() {
return System.identityHashCode(this);
}
}
请检查 equals 方法,如果两个对象相同,它只会返回 true。否则它会破坏为 equals 描述的行为和 hashCode . (准确地说,如果两个对象的哈希码不同,则 equals 方法必须返回 false。)提供符合给定 hashCode() 方法的 equals() 实现:
public boolean equals(Object other){
return this == other;
}
关于基于身份的 Java 哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1063662/