I was just writing code, and suddenly I came across this warning in Netbeans:
hashCode()
called on array instance
It occurred in this piece of code:
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.
}
}
The warning occurs on the marked line. The IDE finds that I should avoid calling hashCode()
on an array instance.
Now why should I avoid using hashCode()
on an array?
Notice that I read this question and answer, but they didn't mention this.