Sobes.tech
Middle

Tell me about the equals and hashCode method contracts in Java.

sobes.tech AI

Answer from AI

  • Reflexivity: for any non-null reference value x, x.equals(x) should return true.

  • Symmetry: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

  • Transitivity: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

  • Consistency: for any non-null reference values x and y, multiple invocations of x.equals(y) should consistently return true or false, provided no information used in equals comparisons on the objects is modified between calls.

  • For any non-null reference value x, x.equals(null) should return false.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, programmers should be aware that producing distinct hash codes for unequal objects may improve the performance of hash tables.

It is important to override both equals and hashCode methods if one of them is overridden to maintain the contract. Using equals without overriding hashCode can lead to incorrect behavior of collections that use hashing (e.g., HashMap, HashSet).

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Reflexivity
        if (o == null || getClass() != o.getClass()) return false; // Null check and type check
        Person person = (Person) o;
        return age == person.age &&
               Objects.equals(name, person.name); // Content comparison
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age); // Hash generation based on fields
    }
}
Tell me about the equals and hashCode method… - sobes.tech