Junior — Middle
How do you implement object equality comparison in your code?
sobes.tech AI
Answer from AI
In Java, to compare objects for equality, the equals(Object obj) method is usually overridden. It is important to follow the contract of the method: reflexivity, symmetry, transitivity, consistency, and null check.
Example implementation:
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // check for reference equality
if (obj == null || getClass() != obj.getClass()) return false; // check for null and class
MyClass other = (MyClass) obj;
return Objects.equals(field1, other.field1) && field2 == other.field2;
}
It is also recommended to override hashCode() so that objects equal according to equals() have the same hash code, which is important for correct operation in collections such as HashMap or HashSet.