Junior — Middle
Is it possible to use the equals method to compare objects in Java?
sobes.tech AI
Answer from AI
Yes, in Java the equals method is used to compare objects for semantic equality, unlike the == operator, which compares references (memory addresses).
By default, the equals method is inherited from the Object class and compares references, but it is often overridden to compare the contents of objects.
Example of overriding equals:
public class Person {
private String name;
private int age;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return age == other.age && Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
It is important to always override hashCode along with equals so that objects work correctly in collections.
In summary, the equals method is the main way to compare objects by content in Java.