Sobes.tech
Junior

What does the equals() method do in Java?

sobes.tech AI

Answer from AI

The equals() method in Java is used to compare the contents of two objects. By default, in the Object class, it compares object references, meaning it determines whether two variables point to the same object in memory.

However, most classes in Java (e.g., String, Integer) override this method to compare the values contained within the objects rather than their references.

When overriding equals(), it is important to adhere to its contract:

  • Reflexivity: x.equals(x) should be true for any non-null x.
  • Symmetry: x.equals(y) should be true if and only if y.equals(x) is true for any non-null x and y.
  • Transitivity: If x.equals(y) and y.equals(z) are true, then x.equals(z) should also be true for any non-null x, y, and z.
  • Consistency: Multiple calls to x.equals(y) should return the same result, provided the objects are not modified.
  • For any non-null x, x.equals(null) should return false.

Example of overriding equals():

class MyObject {
    private int value;

    public MyObject(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        MyObject myObject = (MyObject) obj;
        return value == myObject.value;
    }
}

Using equals():

// Reference comparison (default in Object)
Object obj1 = new Object();
Object obj2 = new Object();
boolean byReference = obj1.equals(obj2); // false

// Value comparison (overridden equals)
MyObject myObj1 = new MyObject(10);
MyObject myObj2 = new MyObject(10);
boolean byValue = myObj1.equals(myObj2); // true

It is also important to override the hashCode() method when overriding equals() to maintain their contract and avoid issues with collections that use hashing (e.g., HashMap, HashSet).

What does the equals() method do in Java? — QA / QA… - sobes.tech