Junior — Middle
What are the main requirements and properties that a method equals should have in Java?
sobes.tech AI
Answer from AI
The equals method in Java must satisfy the following main requirements and properties:
- Reflexivity: For any non-null object
x, the expressionx.equals(x)should returntrue. - Symmetry: For any non-null objects
xandy, the expressionx.equals(y)should returntrueif and only ify.equals(x)returnstrue. - Transitivity: If
x.equals(y)andy.equals(z)returntrue, thenx.equals(z)should also returntrue. - Consistency: Multiple calls to
x.equals(y)should return the same value if the objects are not modified. - Null comparison: For any non-null object
x, the expressionx.equals(null)should returnfalse.
Example implementation of the equals method:
@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 important that when overriding equals, you also override hashCode to maintain the contract between these methods.