Implementation in answer by andersoj
return left != null && right != null && left.equals(p.left) && right.equals(p.right);
false: null tests clearly indicate that null is the legal value for left and right. So there are at least two problems:
new Pair(null, null).hashCode() throws NPEnew Pair(null, null) does NOT match itself!
See the Guava class Objects for a proper implementation. Use it or write static helper methods like
public static boolean equal(Object a, Object b) { return a==b || a!=null && a.equals(b); } public static int hashCode(Object a) { return a==null ? 0 : a.hashCode(); }
and always use them.
Never write equals containing a null test.
It is easy to explode, and no one noticed. Using Helper, it is trivial to figure this out:
public boolean equals(Object o) { if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return Helper.equals(left, p.left) && Helper.equals(right, p.right); } public int hashCode() { return 7 * Helper.hashCode(left) + 13 * Helper.hashCode(right); }
Of course, disabling zeros in the constructor is also an option.
maaartinus
source share