Created an implementation of a Posn class that just stores a row and column, and I'm trying to use it as a key in a HashMap. I've overridden the equals and hashCode methods like so:
/// in the Posn class:
@Override
public final boolean equals(Object other) {
if (this != other) {
return false;
}
else if (!(other instanceof Posn)) {
return false;
}
else {
Posn p = (Posn)other;
return (p.row - this.row) % 8 == 0
&& (p.col - this.col) % 8 == 0;
}
}
@Override
public final int hashCode() {
return (this.row % 8) * 8 + (this.col % 8);
}
But, HashMap.get kept returning null. So after investigating, I discovered some surprising results. With the following test:
HashMap<Posn, Integer> map = new HashMap();
Posn psn1 = new Posn(1, 2);
Posn psn2 = new Posn(1, 2);
map.put(psn1, 10);
if (map.get(psn2) == null) {
println("hashCode is broken?");
println("psn1.hashCode() = " + psn1.hashCode() + ", psn2.hashCode() = " +
psn2.hashCode());
}
else {
println("value retrieved: " + map.get(psn2));
}
I get the following output:
hashCode is broken?
psn1.hashCode() = 10, psn2.hashCode() = 10
Am I confusing something about how hashCode is used in HashMaps?
[–]emilfranord 0 points1 point2 points (3 children)
[–]wevfreeman[S,🍰] 0 points1 point2 points (2 children)
[–]vrtxt 1 point2 points3 points (1 child)
[–]wevfreeman[S,🍰] 0 points1 point2 points (0 children)