Records generate equals and hashCode from their components, so they work as HashMap keys immediately - no boilerplate and no accidental identity comparison.
record CellKey(int row, int col) {}
Map<CellKey, String> sheet = new HashMap<>();
sheet.put(new CellKey(1, 1), "A1");
sheet.put(new CellKey(2, 5), "B5");
System.out.println("lookup with a new instance: " + sheet.get(new CellKey(1, 1)));
System.out.println("equal keys do not duplicate: size = " + sheet.size());
sheet.put(new CellKey(1, 1), "A1-updated");
System.out.println("after overwrite: size = " + sheet.size() + ", value = " + sheet.get(new CellKey(1, 1)));
lookup with a new instance: A1
equal keys do not duplicate: size = 2
after overwrite: size = 2, value = A1-updated
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30