javajava-14java-record

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


Assuming the following example:

public record SomeRecord(int foo, byte bar, long baz)
{ }

Do I need to override hashCode and equals if I were to add said object to a HashMap?


Solution

  • 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.