我正在编写代码,突然在 Netbeans 中遇到了这个警告:
hashCode()
called on array instance
它发生在这段代码中:
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 ,但他们没有提到这一点。
最佳答案
Java 数组直接派生自 java.lang.Object
,因此继承了 equals
和 hashCode
方法。
默认的equals
方法比较对象身份(即两个引用是否引用同一个对象),默认的hashCode
方法将最可能为不同的对象返回不同的值。
在大多数情况下,这是您不希望出现的行为。您很可能希望根据内容来比较数组。请注意,您的 equals 方法似乎可以做到这一点,这反过来意味着您的 hashCode 方法已损坏。看method's documentation因为这个原因。
正是出于这个原因,Java 提供了一个带有辅助方法的类:java.util.Arrays
。它提供了 equals
和 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) && Arrays.equals(this.b, object.b));
}
@Override
public int hashCode() {
return (43 * this.a.hashCode() + 11 * Arrays.hashCode(this.b));
}
}
关于java - 在 Java 中对数组实例调用 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24385571/