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 betruefor any non-nullx. - Symmetry:
x.equals(y)should betrueif and only ify.equals(x)istruefor any non-nullxandy. - Transitivity: If
x.equals(y)andy.equals(z)aretrue, thenx.equals(z)should also betruefor any non-nullx,y, andz. - 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 returnfalse.
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).