Every class except Object extends it, directly or through its ancestors, so every object has equals, hashCode and toString. The defaults are weak: equals compares references (like ==), hashCode is tied to the object's identity, not its values, and toString gives the class name, @ and the hash code in hex. To compare objects by value, override all three.
WHAT EQUALS PROMISES
x.equals(x)x.equals(y)x.equals(y)∧y.equals(z)x.equals(null)=true⇒y.equals(x)⇒x.equals(z)=false
For all non-null x, y, z. Lines 1 to 3 make equals reflexive (an object equals itself), symmetric (order does not matter) and transitive (equality passes along a chain). Repeated calls must give the same answer while the compared fields are unchanged.
WHAT HASHCODE PROMISES
x.equals(y)⇒x.hashCode()=y.hashCode()
For all non-null x, y. The reverse is not required: unequal objects may share a hash code. Repeated calls must return the same value while those fields are unchanged. If you override equals, override hashCode too, using only fields that equals compares.
WHY THE PROMISE IS NEEDED
bucket=hmodn
A simplified model of a new HashSet<>(): n buckets (a power of 2; 16 at first), int hash code h, bucket 0 to n − 1. Java first mixes the high bits of h into the low ones, which changes nothing while 0 ≤ h < 65,536. The set searches one bucket and calls equals only on entries with the same h, so equal objects with different h are never found.
final class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override public int hashCode() { return 31 * x + y; }
@Override public String toString() { return "Point(" + x + "," + y + ")"; }
}
public class PointDemo {
public static void main(String[] args) {
Point p = new Point(3, 4), q = new Point(3, 4);
System.out.println(p + " " + p.equals(q) + " " + (p == q));
}
}
// Point(3,4) true false
The parameter must be Object. o instanceof Point is true when o refers to a Point and false for null, so null is covered. The cast (Point) o then lets you read p.x and p.y. Joining a string with + calls toString. The class is final: a subclass that added a colour field and compared it in its own equals would break symmetry, since a Point could equal a coloured point that does not equal it back.