Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 206
shavit Avatar asked May 10 '20 22:05

shavit


1 Answers

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.

like image 175
sprinter Avatar answered Sep 21 '22 05:09

sprinter