我在 HashMap 的上下文中读过某处:
hashCode() allows sorting objects by their hash values, and then the Object#equals method only needs to be invoked when objects share the same hash value.
是否意味着最终调用 equals() 方法时,已经比较了 hashCode 并发现必然相等?这种情况有什么例外吗?
问题的第二部分:在 equals() 方法中检查两个对象的 hashCode() 是否有意义?
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof InternalObjectSerialized)) {
return false;
}
InternalObjectSerialized<?> inputObj = (InternalObjectSerialized<?>) obj;
if (!(Arrays.equals(this.bytes, inputObj.bytes))) {
return false;
}
// …
Run Code Online (Sandbox Code Playgroud)