我正在使用Java 7,並且我在下面有下面的類。我正確實施了equals
和hashCode
,但問題是equals
在下面的主要方法中返回false
,但hashCode
返回兩個對象的相同哈希碼。我可以多看一些眼睛來看看這個班級,看看我在這裏做錯了什麼嗎?equals和hashCode:是否Objects.hash方法被破壞?
更新:我用我自己的散列函數替換了我稱之爲Objects.hash
方法的行:chamorro.hashCode() + english.hashCode() + notes.hashCode()
。它返回一個不同的哈希碼,這是兩個對象不同時應該做的hashCode
。 Objects.hash
方法是否被破壞?
您的幫助將不勝感激!
import org.apache.commons.lang3.StringEscapeUtils;
public class ChamorroEntry {
private String chamorro, english, notes;
public ChamorroEntry(String chamorro, String english, String notes) {
this.chamorro = StringEscapeUtils.unescapeHtml4(chamorro.trim());
this.english = StringEscapeUtils.unescapeHtml4(english.trim());
this.notes = notes.trim();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof ChamorroEntry)) {
return false;
}
if (this == object) {
return true;
}
ChamorroEntry entry = (ChamorroEntry) object;
return chamorro.equals(entry.chamorro) && english.equals(entry.english)
&& notes.equals(entry.notes);
}
@Override
public int hashCode() {
return java.util.Objects.hash(chamorro, english, notes);
}
public static void main(String... args) {
ChamorroEntry entry1 = new ChamorroEntry("Åguigan", "Second island south of Saipan. Åguihan.", "");
ChamorroEntry entry2 = new ChamorroEntry("Åguihan", "Second island south of Saipan. Åguigan.", "");
System.err.println(entry1.equals(entry2)); // returns false
System.err.println(entry1.hashCode() + "\n" + entry2.hashCode()); // returns same hash code!
}
}
兩個對象具有相同的哈希代碼,但仍然不相等。所以這個問題不是用'Objects.hash',對吧? –
@RayToal這很好,但很愚蠢。考慮到有40億個可能的值,碰撞應該是非常高的速度,你不應該通過手動嘗試幾個值來碰到它們。由於重複使用相同的乘數是造成這種效率低下的原因,因此'Objects.hash'有點像設計*。 – maaartinus