Junior — Middle
How is the equals method implemented in Java and how is it used to compare objects?
sobes.tech AI
Answer from AI
In Java, the equals() method is defined in the Object class and is used to compare objects for logical equality. By default, it compares references (i.e., checks whether two variables point to the same object).
For correct comparison of object contents, classes usually override the equals() method to compare meaningful fields of objects.
Example of overriding equals():
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // identity check
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 ensure correct behavior of objects in collections, such as in HashMap.
Usage:
MyClass a = new MyClass(...);
MyClass b = new MyClass(...);
if (a.equals(b)) {
// objects are considered equal by content
}