Sobes.tech
Junior

What does the equals() method do in Java?

sobes.tech AI

Answer from AI

The equals() method in Java compares two objects for equality.

By default, in the base class Object, the implementation of equals() is equivalent to the == operator, meaning it checks whether two variables refer to the same object in memory.

However, for many user-defined classes, such as strings (String) or collections, this method is overridden to compare objects based on their content (logical equality), rather than references.

When overriding equals(), the following characteristics must be observed:

  • 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.
  • For any non-null reference value x, x.equals(null) should return false.

It is also important that when overriding equals(), the hashCode() method should also be overridden, as they are closely related. If two objects are considered equal according to equals(), their hash codes returned by hashCode() should be the same.

Example of overriding equals() for a simple class:

public class MyClass {
    private int id;
    private String name;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyClass myClass = (MyClass) o;
        return id == myClass.id &&
               Objects.equals(name, myClass.name);
    }

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