Sobes.tech
Middle

What are the rules for the equals and hashCode methods?

sobes.tech AI

Answer from AI

  1. If two objects are equal according to the equals(Object) method, their hash codes (returned by the hashCode() method) must be the same.
  2. If two objects are not equal according to the equals(Object) method, their hash codes may be the same or different. It is good practice to ensure different hash codes for unequal objects for better performance of hash-based collections.
  3. The hashCode() method should return the same value for the same object across multiple calls, provided that no information used in the hash code calculation has changed.
  4. Symmetry: for any objects a and b, if a.equals(b) is true, then b.equals(a) should also be true.
  5. Reflexivity: for any non-null object a, a.equals(a) should be true.
  6. Transitivity: for any objects a, b, and c, if a.equals(b) is true and b.equals(c) is true, then a.equals(c) should also be true.
  7. Consistency: for any non-null objects a and b, multiple invocations of a.equals(b) should consistently return true or false, provided that no information used in the equals(Object) comparisons has changed.

Example implementation:

public class MyClass {

    private int value;
    private String name;

    public MyClass(int value, String name) {
        this.value = value;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        // Check object identity
        if (this == o) {
            return true;
        }
        // Check object type
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        // Cast to the correct type
        MyClass myClass = (MyClass) o;
        // Compare fields
        return value == myClass.value &&
               Objects.equals(name, myClass.name); // Use Objects.equals to handle nulls
    }

    @Override
    public int hashCode() {
        // Use Objects.hash to generate hash code based on fields
        return Objects.hash(value, name);
    }

    // Other methods...
}