Record Basics

One Line Instead of Fifty

A record is a class whose job is to hold data. From record Point(int x, int y) Java generates:

  • private final fields x and y
  • a constructor taking all fields (the canonical constructor)
  • accessor methods x() and y() (no get prefix)
  • equals, hashCode and toString based on all fields

Using a Record

Example

import java.util.HashSet;
import java.util.Set;

public class Main {
    record Point(int x, int y) { }

    public static void main(String[] args) {
        Point a = new Point(3, 4);
        Point b = new Point(3, 4);
        System.out.println(a);
        System.out.println("x=" + a.x() + ", y=" + a.y());
        System.out.println("equals: " + a.equals(b) + ", == : " + (a == b));

        Set<Point> visited = new HashSet<>();
        visited.add(a);
        System.out.println("contains (3,4)? " + visited.contains(new Point(3, 4)));
    }
}

Output

Point[x=3, y=4]
x=3, y=4
equals: true, == : false
contains (3,4)? true

The Same Thing as a Class

// What "record Point(int x, int y) { }" replaces:
final class Point {
    private final int x;
    private final int y;

    Point(int x, int y) { this.x = x; this.y = y; }

    public int x() { return x; }
    public int y() { return y; }

    @Override public boolean equals(Object o) {
        return o instanceof Point p && p.x == x && p.y == y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
    @Override public String toString() { return "Point[x=" + x + ", y=" + y + "]"; }
}