Easy java core-java

What is the difference between == and equals(), and why must hashCode() match equals()?

The 30 second answer

For objects, == checks whether two references point to the same object, and equals checks whether they are logically equal. Object's default equals is the same as ==, so value classes override it. The contract says that equal objects must have the same hashCode, because HashMap and HashSet first use the hash to find a bucket and then call equals. If I override equals without hashCode, two equal keys land in different buckets and the map can't find them. Records generate both for me.

<!-- level: 1 --> <!-- must_know: true -->

  • == on primitives compares values. On references it compares identity: is it the same object?
  • equals(Object) compares logical equality. Object.equals returns true only for the same object, so classes like String, Integer and your value objects override it.

The Object.hashCode contract in the Javadoc:

  • If two objects are equal according to equals, calling hashCode on each must produce the same integer.
  • Two unequal objects may share a hash code, but distinct hash codes improve hash table performance.
  • hashCode must stay the same during one execution as long as the fields used by equals don't change.
String s1 = "java", s2 = "java", s3 = new String("java");
s1 == s2;       // true: both literals are the same pooled object
s1 == s3;       // false: new String creates a separate object
s1.equals(s3);  // true: same characters

Practical rules: override both or neither, base them on the same fields, prefer immutable fields for keys, and use a record when the class is a plain value carrier because it generates equals, hashCode and toString. What breaks when you skip equals is shown in Two Employee objects with identical data compared; equals() never overridden?.

Sources (1)
  1. Javadoc: java.lang.Object (equals and hashCode)docs.oracle.com