What are records in Java, and what does the compiler generate for you?
A record is a class that holds data and nothing else, and the compiler writes the repetitive parts for you.
You write the list of values that the record holds, and the compiler gives you the field, the constructor, the way to read the values, the way to compare two records, the way to work out a hash code, and the text form.
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// The whole class is two lines long.
record Person(String name, int age) {}
Person first = new Person("Ada", 36);
Person second = new Person("Ada", 36);
System.out.println("the name : " + first.name());
System.out.println("the age : " + first.age());
System.out.println("the text : " + first);
System.out.println("same value: " + first.equals(second));
System.out.println("same hash : " + (first.hashCode() == second.hashCode()));
// A record works in a set and in a map key.
Set<Person> people = new HashSet<Person>();
people.add(first);
people.add(second);
System.out.println("the set holds : " + people.size() + " person");
}
}
So what does the compiler actually generate? It writes a private final field for each of the values you listed. It writes a constructor that takes them in that order. It writes a method to read each one, and the name of that method is the name of the value itself, so name() and not getName(). It writes an equals method that compares the values, a hash code method that is worked out from the values, and a text form that lists them.
There is one more thing that the compiler does that is worth knowing. A record is always final, and its fields are always final, so it can never change after it has been made.
The next question in this topic looks at the limits.