Junior — Middle
How does the equals method perform comparison of two objects in Java?
sobes.tech AI
Answer from AI
The equals method in Java is used to compare two objects for semantic equality. By default, if not overridden, it compares references (i.e., checks whether the objects point to the same instance).
When overriding equals, it is common to compare the contents of objects, such as the values of fields.
A typical implementation of equals includes:
- Checking reference equality (
this == obj) - Checking for
nulland class compatibility - Comparing significant fields of the objects
Example:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return Objects.equals(field1, other.field1) && field2 == other.field2;
}
It is also important to override hashCode when overriding equals to maintain the contract between these methods.