Intermediate 8 min
Records and value equality
A record is a compact way to define a data carrier with named components.
How it works
Think of a record as data with a name for each part. Declare x and y and Java produces accessors plus equality based on those components. You can still add validation, for example rejecting a negative quantity in a compact constructor.
Walk through an example
A Point(int x, int y) record gives you accessors x() and y() and component-based equality. Two independently constructed points with x equal to 1 and y equal to 2 compare equal.
What to watch for
A record’s component references are final. Making a record with a mutable list still leaves that list mutable unless you make a defensive copy.
Code example
public class Main {
record Point(int x, int y) {}
public static void main(String[] args) {
System.out.println(new Point(1, 2).equals(new Point(1, 2)));
}
}Check your understanding
What boolean is produced?
See the example and explanation
- Worked example
- Given
record Point(int x, int y) {}; new Point(1, 2).equals(new Point(1, 2)) - Answer
true
The generated equals operation compares both component values, and both coordinates match.