Junior — Middle
What are the main characteristics of the equals method in Java?
sobes.tech AI
Answer from AI
The equals method in Java is used to compare objects for logical equality. Main characteristics:
- Symmetry:
a.equals(b)should be equal tob.equals(a). - Reflexivity: an object should be equal to itself (
a.equals(a)returns true). - Transitivity: if
a.equals(b)andb.equals(c)thena.equals(c). - Consistency: multiple calls to
equalswith the same objects should return the same result. - Inequality with null:
a.equals(null)always returns false.
Example of overriding 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;
}