liveBook · Manning

Java record

As explained in 100 Java Mistakes and How to Avoid Them

A Java record is a restricted class declaration for modeling data-carrier objects with a compact syntax for components and associated members.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains compiler-generated equals() and hashCode(), but does not detail record syntax or component semantics.
Examples
Uses malformed hand-written equals() implementations, IDE generation dialogs, and EqualsVerifier as practical comparisons.
What you can do after
Evaluate when records can replace manual equals() and hashCode() implementations.
How it connects
Connects records with equals(), hashCode(), IDE generation, Objects.equals(), and EqualsVerifier.

Also explained in

Compare how 4 books explain Java record →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.