A Java record is a compact data-carrier class whose equals() and hashCode() implementations are generated automatically by the compiler. It reduces the risk of errors common in hand-written equality methods. section 7.6 section 7.15
Why records help
Manual equals() implementations can compare the wrong field, omit a field, or mishandle null values. Replacing eligible data classes with records delegates equals() and hashCode() generation to the compiler. section 7.6
Use records as a safeguard when:
- A class primarily stores data and needs value-based equality. section 7.6
- Hand-written equals() and hashCode() methods would otherwise require repeated maintenance when fields change. section 7.6
- A regular class must remain in use; generate equality with IDE tooling and test it with EqualsVerifier. section 7.6
class MyEntity {
private String name;
private List<String> attributes;
private Object data;
private long timeStamp;
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyEntity other = (MyEntity) o;
return timeStamp == other.timeStamp &&
name.equals(other.name) &&
attributes.equals(attributes) &&
data.equals(other.data);
}
}
Inspect this malformed equals() implementation to see the kinds of field-comparison mistakes that records can help avoid. section 7.6



