All 15 equals(), hashCode() & toString() Contracts questions
More in equals(), hashCode() & toString() Contracts
Advertisement
Back to results for “Java Fundamentals: Syntax”
Java › equals(), hashCode() & toString() Contracts

How does Objects.equals() and Objects.hash() from java.util.Objects simplify writing correct equals() and hashCode() implementations, particularly regarding null-safety?

Intermediate

Answer

Objects.equals(a, b) performs a null-safe equality check (returning true if both are null, false if only one is null, and delegating to a.equals(b) otherwise), avoiding the need to manually null-check each field being compared; Objects.hash(fields...) computes a combined hash code across multiple fields (internally similar to Arrays.hashCode() on an array of the boxed field values), both significantly reducing the boilerplate and null-handling bugs common in hand-written equals()/hashCode() implementations, especially for classes with several nullable fields.
public class Person {
    private final String name;
    private final String email;  // nullable

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Person p)) return false;
        return Objects.equals(name, p.name) && Objects.equals(email, p.email);  // null-safe
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, email);  // handles null fields automatically
    }
}
Real-world example A Person class with a nullable email field uses Objects.equals() for field comparison and Objects.hash() for hashCode generation, avoiding the NullPointerException risk that manual field.equals(other.field) calls would introduce whenever the email field happens to be null for either compared instance.

Common follow-ups: What's the performance overhead of Objects.hash()'s varargs array creation compared to manually combining hash codes?;How do IDE-generated equals()/hashCode() methods typically differ from using Objects.equals()/hash()?