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 returntrue. - Symmetry: For any non-null reference values
xandy,x.equals(y)should returntrueif and only ify.equals(x)returnstrue. - Transitivity: For any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue. - Consistency: For any non-null reference values
xandy, multiple invocations ofx.equals(y)should consistently returntrueorfalse, provided no information used inequalscomparisons on the objects is modified. - For any non-null reference value
x,x.equals(null)should returnfalse.
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);
}
}