hjf*_*yer 11 java identity hashcode
Object.hashCode()的默认行为是返回对象的"地址",以便当且仅当a == b时,a.hashCode()== b.hashCode().如果超类已经定义了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);
}
}
Run Code Online (Sandbox Code Playgroud)
想法?
Mne*_*nth 26
System.identityHashCode(Object)提供此行为.
你会写这个:
class B extends A {
public int hashCode() {
return System.identityHashCode(this);
}
}
Run Code Online (Sandbox Code Playgroud)
如果两个对象相同,请检查equals-method,它只返回true.否则它会破坏为equals和hashCode描述的行为.(为了正确,如果为两个对象获得不同的哈希码,则equals-method必须返回false.)提供符合给定hashCode()方法的equals()实现:
public boolean equals(Object other){
return this == other;
}
Run Code Online (Sandbox Code Playgroud)
使用System.identityHashCode().这就是IdentityHashMap用途.
你应该非常谨慎地覆盖现有hashCode()的这个,因为你可能会破坏hashCode契约,因为这两个对象:
如果a.equals(b)那么a.hashCode()必须等于b.hashCode()
您可以通过覆盖现有行为来解决此问题,或者您也可能需要覆盖equals().
| 归档时间: |
|
| 查看次数: |
2282 次 |
| 最近记录: |