Skip to main content
equals, hashCode, compareTo · Topic 6 of 6

Objects.hash and records

Definition​

Objects.equals and Objects.hash make equals and hashCode short and null-safe. A record goes further: Java writes correct equals, hashCode and toString for you from the fields.

Example code​

Hand-written, with Objects helpers, and with a record

import java.util.Objects;

class Customer {
private final String name;
private final String city;

Customer(String name, String city) { this.name = name; this.city = city; }

@Override public boolean equals(Object o) {
return o instanceof Customer c && Objects.equals(name, c.name) && Objects.equals(city, c.city); // null-safe
}

@Override public int hashCode() { return Objects.hash(name, city); }
}

record CustomerRecord(String name, String city) { } // all three methods generated

class Demo {
public static void main(String[] args) {
System.out.println(new Customer("Asha", null).equals(new Customer("Asha", null)));
System.out.println(new CustomerRecord("Asha", "Pune").equals(new CustomerRecord("Asha", "Pune")));
System.out.println(new CustomerRecord("Asha", "Pune"));
}
}

// Output:
// true
// true
// CustomerRecord[name=Asha, city=Pune]

Finished this page? Track your progress (saved only in your browser).