【发布时间】:2014-06-24 11:34:45
【问题描述】:
我刚写代码,突然在Netbeans中看到这个警告:
hashCode()在数组实例上调用
发生在这段代码中:
public class SomeObject {
private String a;
private char[] b;
@Override
public boolean equals(Object anotherObject) {
if (!(anotherObject instanceof SomeObject)) {
return false;
}
SomeObject object = (SomeObject) anotherObject;
return (this.a.equals(object.a) && arraysAreEqual(this.b, object.b));
}
// When I created the equals() method, Netbeans warned me:
// 'Generate missing hashCode()'. Okay then, here it comes:
@Override
public int hashCode() {
return (43 * this.a.hashCode() + 11 * this.b.hashCode()); // MARKED LINE.
}
}
警告出现在标记的行上。 IDE 发现我应该避免在数组实例上调用 hashCode()。
现在我为什么要避免在数组上使用hashCode()?
请注意,我阅读了this question and answer,但他们没有提到这一点。
【问题讨论】:
-
如果内存服务,数组继承默认的
hashCode()实现,所以也许这就是原因。 -
Riiight。这就说得通了。似乎这个问题有它的重复。