我在 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;
}
// Does the following line make any sense ??
return this.hashCode() == inputObj.hashCode();
}
总结一下评论:
在Java中,在Object#equals()调用期间,两个对象是否必须具有相同的hashCode?
彼此
.equals
的两个对象确实需要具有相同的hashCode,但您需要编写equals方法和hashCode方法来确保这是正确的。
我们需要在 equals() 中比较 hashCode 吗?
不,您不需要在
.equals
的实现中比较 hashCode,如果事实上您不应该这样做。