Do you need to override hashCode() and equals() for records?

No you do not need to define your own hashCode and equals. You may do so if you wish to override the default implementation.

See section 8.10.3 of the specification for details https://docs.oracle.com/javase/specs/jls/se14/preview/specs/records-jls.html#jls-8.10

Note, specifically, the caveat on implementing your own version of these:

All the members inherited from java.lang.Record. Unless explicitly
overridden in the record body, R has implicitly declared methods that
override the equals, hashCode and toString methods from
java.lang.Record.

Should any of these methods from java.lang.Record be explicitly
declared in the record body, the implementations should satisfy the
expected semantics as specified in java.lang.Record.

In particular, a custom equals implementation must satisfy the expected semantic that a copy of a record must equal the record. This is not generally true for classes (e.g. two Car objects might be equals if their VIN value is the same even if owner fields are different) but must be true for records. This restriction would mean that there is rarely any reason to override equals.

Leave a Comment