equals
和hashCode
,但问题是在下面的主方法中equals
返回false
,但hashCode
为两个对象返回相同的哈希码。我能否请更多人来查看这个类,看看我是否有任何错误?
更新:我用自己的哈希函数替换了调用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
,对吧? - Ray ToalObjects.hash
在设计上有点愚蠢,因为重复使用相同的乘数会导致这种低效率。 - maaartinus