Video in progress
How do equals and hashCode behave when you use a record with an array or List component as a HashMap key or HashSet element?
A record compares each component with Objects.equals. For an array that means reference equality, so two records holding arrays with the same contents are not equal. A List component is compared by contents, but if the list is mutable, the key can get "lost" inside the Map.
📖 Answer
record Key(String type, int[] parts) {}
var a = new Key("x", new int[]{1, 2});
var b = new Key("x", new int[]{1, 2});
a.equals(b); // false
new HashSet<>(List.of(a, b)).size(); // 2
A record's generated equals compares the array by reference, not with Arrays.equals, and hashCode takes the array's identity hash. javac doesn't warn about this; an IDE sometimes does.
There are two ways out: use a List<Integer> instead of an array, or write equals/hashCode yourself (Arrays.equals, Arrays.hashCode). If you keep the array, you also need to copy it in the constructor, otherwise outside code can modify the array and break the record's "immutability".
Another trap, with a List component:
record Route(String from, List<String> stops) {}
var stops = new ArrayList<>(List.of("A", "B"));
var r = new Route("X", stops);
prices.put(r, 10);
stops.add("C"); // r.hashCode() changed
prices.get(r); // null
A record is only shallowly immutable: the field reference is final, but the list inside is not. So writing stops = List.copyOf(stops); in the compact constructor should become a habit. Then the record is genuinely fit to be a key, and outside code can't break it.
In interviews this question is often asked to test the idea that "if it's a record, you don't have to think about equals/hashCode". You do, unless the components are value types themselves.
Sign up to mark studied questions and save your progress.