Junior — Middle
What is the role of the equals method in the Object class in Java?
sobes.tech AI
Answer from AI
The equals method in the Object class in Java is used to compare objects for equality. By default, it compares references, meaning it returns true if both variables point to the same object in memory.
However, in most cases, it is necessary to compare objects by their content, so classes override the equals method to implement logic for comparing significant fields.
Example of overriding equals in the Person class:
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 also important to override hashCode along with equals so that objects work correctly in collections such as HashMap and HashSet.