Sub topic 14
Records: generated equals, hashCode, and toString
This chapter assumes you have read the earlier chapters on the equals and hashCode contracts, how HashMap and HashSet use them, and the inheritance pitfalls. It also assumes you know Java 16 or later syntax at the level of instanceof pattern matching. Records are the language's answer to the boilerplate you wrote by hand in earlier chapters.
What a record declares
A record is a class designed to be a transparent carrier for a fixed set of values. You list the values, called components, in the header:
public record Point(int x, int y) {}From this header the compiler generates:
- a private final field for each component
- a canonical constructor that takes every component and assigns it
- an accessor method per component, named after the component (
x(), notgetX()) equals,hashCode, andtoString
A record is implicitly final and implicitly extends java.lang.Record. It cannot extend another class, though it can implement interfaces. Because it is final, the subclass symmetry problem from the inheritance chapter cannot occur.
The generated behavior
Run this to see all three methods at work:
public class RecordBasics {
record Point(int x, int y) {}
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
System.out.println(a); // Point[x=1, y=2]
System.out.println(a.x()); // 1
}
}The rules behind this output are worth knowing precisely.
- equals returns true when the argument is an instance of the same record class and every component is equal. Primitive components are compared as the matching wrapper class's
comparemethod would compare them. Reference components are compared withObjects.equals, sonullis handled. - hashCode is derived from the component hash codes. The exact algorithm is unspecified. It is guaranteed consistent with
equals, but never hard-code or persist a specific value. - toString has the form
TypeName[component=value, ...]. The format is conventional, not a contract you should parse.
Floating-point components
Because double components use Double.compare semantics, records behave like the Sample class from the field types chapter, not like the == operator:
public class RecordDoubles {
record Score(double value) {}
public static void main(String[] args) {
System.out.println(new Score(Double.NaN).equals(new Score(Double.NaN))); // true
System.out.println(new Score(0.0).equals(new Score(-0.0))); // false
System.out.println(Double.NaN == Double.NaN); // false
System.out.println(0.0 == -0.0); // true
}
}This keeps equals reflexive for NaN, which the contract requires.
Shallow immutability
The fields of a record are final, but final only protects the reference, not the object it points to. A record with a mutable component is only shallowly immutable. This brings back two pitfalls from earlier chapters:
- If a component is a mutable object whose state affects its
hashCode, mutating it after the record is used as aHashMapkey makes the entry unreachable. This is the mutable key problem again. - If a component is an array, the generated methods use array identity, not content.
The array case is the most common surprise:
import java.util.Arrays;
public class RecordArrays {
record Bad(int[] values) {}
public static void main(String[] args) {
Bad p = new Bad(new int[] {1, 2});
Bad q = new Bad(new int[] {1, 2});
System.out.println(p.equals(q)); // false: arrays compared by reference
System.out.println(p); // Bad[values=[I@...] (not readable)
System.out.println(Arrays.toString(p.values())); // [1, 2]
}
}Compact constructors: validation and defensive copies
You can customize construction without writing out the assignments. A compact canonical constructor has no parameter list. It runs your code first, and the compiler then assigns the fields from the parameters. You may reassign the parameters inside it, which is how you normalize or copy.
import java.util.List;
import java.util.Objects;
public class RecordValidation {
record Order(String id, List<String> items) {
Order {
Objects.requireNonNull(id, "id");
if (id.isBlank()) {
throw new IllegalArgumentException("id must not be blank");
}
items = List.copyOf(items); // defensive copy; rejects null elements
}
}
public static void main(String[] args) {
List<String> source = new java.util.ArrayList<>(List.of("pen"));
Order o = new Order("A-1", source);
source.add("ink"); // does not affect the record
System.out.println(o);
}
}This prints Order[id=A-1, items=[pen]]. The copy in the constructor is what protects the generated equals and hashCode from later changes to the caller's list. Validating in the constructor also means every instance in existence is valid, so equality never has to deal with half-built values.
Overriding the generated methods
You can declare any of the three methods yourself. When you do, your version replaces the generated one, and the contracts become your responsibility again. Always use @Override so a wrong signature is a compile error, as the overload chapter showed.
A useful case is an array-holding record that compares by content:
import java.util.Arrays;
public class RecordArrayFixed {
record Good(int[] values) {
Good {
values = values.clone();
}
@Override
public int[] values() {
return values.clone();
}
@Override
public boolean equals(Object o) {
return o instanceof Good g && Arrays.equals(values, g.values);
}
@Override
public int hashCode() {
return Arrays.hashCode(values);
}
@Override
public String toString() {
return "Good" + Arrays.toString(values);
}
}
public static void main(String[] args) {
Good a = new Good(new int[] {1, 2});
Good b = new Good(new int[] {1, 2});
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
System.out.println(a); // Good[1, 2]
}
}The constructor clones on the way in and the accessor clones on the way out, so no outside code holds a reference to the internal array.
Another reason to override is to define equality on a subset of components. For example, an Employee(long id, String name) record might treat two employees with the same id as equal. That is legitimate, but then hashCode must use only id as well. It also means the generated toString still shows name, which can surprise readers. Decide deliberately, and document it.
Records as hash keys
Records suit keys in maps and elements in sets because their equality is value-based and their fields cannot be reassigned:
import java.util.HashMap;
import java.util.Map;
public class RecordKeys {
record Coord(int row, int col) {}
public static void main(String[] args) {
Map<Coord, String> board = new HashMap<>();
board.put(new Coord(0, 1), "rook");
System.out.println(board.get(new Coord(0, 1))); // rook
}
}The lookup works because the two Coord objects are distinct but equal, and their hash codes match. This is the guarantee you built by hand in the hashCode chapter, now free.
When not to use a record
Records fit data carriers. Choose a regular class when:
- the object has identity and a lifecycle, such as a database connection or a session, so value equality would be wrong
- you need mutable state or fields that are not part of the public state
- you need to extend another class
- equality should depend on something other than the declared components, and the override would fight the design
Testing record equality
You rarely need to test the generated methods themselves, since the language guarantees them. Test what you wrote: constructor validation, defensive copies, and any overridden equals and hashCode. For overrides, apply the checks from the testing chapter. A short check for the Order record above might assert that mutating the source list leaves equals unchanged:
import java.util.ArrayList;
import java.util.List;
public class OrderCopyCheck {
record Order(String id, List<String> items) {
Order {
items = List.copyOf(items);
}
}
public static void main(String[] args) {
List<String> src = new ArrayList<>(List.of("pen"));
Order before = new Order("A-1", src);
Order same = new Order("A-1", List.of("pen"));
src.add("ink");
System.out.println(before.equals(same)); // true
System.out.println(before.hashCode() == same.hashCode()); // true
}
}Summary
| Aspect | Generated by a record | Your responsibility |
|---|---|---|
| `equals` | Same class, all components equal | Override only for array components or a deliberate subset |
| `hashCode` | Consistent with `equals`, algorithm unspecified | Keep consistent if you override `equals` |
| `toString` | `Name[a=1, b=2]` | Override for arrays or sensitive fields such as passwords |
| Immutability | Fields are final (shallow) | Copy mutable components in the constructor |
| Inheritance | Final, no superclass | Use interfaces for shared behavior |
Exercise
A record Basket(String owner, int[] counts) is used as a HashMap key. Two baskets are built with equal owners and arrays containing the same numbers. Will map.get(secondBasket) find the value stored under the first? Why, and what are two ways to fix it?
Show answer
No. The generated equals and hashCode treat the array component by reference, so the two records are not equal and their hash codes almost certainly differ. Fix it either by replacing int[] with an unmodifiable List<Integer> created with List.copyOf in a compact constructor, or by overriding equals with Arrays.equals, hashCode with Arrays.hashCode, and toString with Arrays.toString, while cloning the array in the constructor and accessor.
Exercise
What does new Score(0.0).equals(new Score(-0.0)) return for record Score(double value) {}, and which rule of the generated equals explains it?
Show answer
It returns false. Primitive components are compared with the wrapper's compare method, here Double.compare, which orders -0.0 before 0.0 and so does not treat them as equal. The same rule makes two NaN values equal, which keeps equals reflexive.
Exercise
You write record User(long id, String name) and override equals to compare only id. What must you also change, and what does the generated toString still reveal?
Show answer
You must override hashCode to use only id, so equal users have equal hash codes. The generated toString still prints both id and name, so you may want to override it if that is misleading.