CKTIS / Java
Records and aggregate values in Java
Records and aggregate values in Java: A Java 21 record is a nominal, shallowly immutable aggregate class: its component list determines private final fields, public accessors, a canonical constructor, and equals, hashCode, and toString.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
records aggregatesA Java 21 record is a nominal, shallowly immutable aggregate class: its component list determines private final fields, public accessors, a canonical constructor, and equals, hashCode, and toString.
Use a record for values, messages, and keys whose state is a fixed set of components; put validation and normalization in its canonical or compact constructor.
A component reference is final but its referent may remain mutable; an array component uses the array’s equals, which is identity-based rather than Arrays.equals.
A record is implicitly final and directly extends java.lang.Record; compact-constructor fields are assigned after its body and cannot be assigned explicitly, while a nested record is implicitly static.
The record prints Point[x=2, y=3], equal=true, and sum=5; defensive copies preserve snapshot=[1, 2], while array-based equals yields same-contents-equal=false.
Examples
import java.util.Arrays;
public class Main {
record Point(int x, int y) {
Point {
if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
}
int sum() { return x + y; }
}
record Snapshot(String name, int[] values) {
Snapshot { values = values.clone(); }
@Override public int[] values() { return values.clone(); }
}
public static void main(String[] args) {
var point = new Point(2, 3);
System.out.println(point);
System.out.println("equal=" + point.equals(new Point(2, 3)));
System.out.println("sum=" + point.sum());
int[] source = {1, 2};
var snapshot = new Snapshot("v1", source);
source[0] = 9;
snapshot.values()[1] = 8;
System.out.println("snapshot=" + Arrays.toString(snapshot.values()));
System.out.println("same-contents-equal=" + snapshot.equals(new Snapshot("v1", new int[]{1, 2})));
}
}
Result
Point[x=2, y=3] equal=true sum=5 snapshot=[1, 2] same-contents-equal=false
The record prints Point[x=2, y=3], equal=true, and sum=5; defensive copies preserve snapshot=[1, 2], while array-based equals yields same-contents-equal=false.