Sobes.tech
Junior

What is the purpose of the equals method in Java?

sobes.tech AI

Answer from AI

The equals method in Java is used for object comparison. By default, it checks if two variables refer to the same object in memory. Classes can override this method to implement custom comparison logic based on the internal state of objects.

Typically, when overriding equals, the following rules are followed:

  • Reflexivity: For any non-null reference x, x.equals(x) should return true.
  • Symmetry: For any non-null references x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • Transitivity: For any non-null references x, y, and z, if x.equals(y) and y.equals(z) are true, then x.equals(z) should be true.
  • Consistency: Multiple invocations of x.equals(y) should consistently return the same result, provided no information used in equality comparisons is modified.
  • x.equals(null) should return false.

It is also important to override hashCode whenever equals is overridden, to maintain the contract: if two objects are equal according to equals, their hash codes must be the same.

Example override:

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; // Reference check
        if (o == null || getClass() != o.getClass()) return false; // Null and type check
        Person person = (Person) o; // Type cast
        return age == person.age && // Compare age
               Objects.equals(name, person.name); // Compare name, null-safe
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age); // Generate hash code based on fields
    }
    // Getters and other methods...
}