Junior — Middle
What is the purpose of the equals() method in the base Object class in Java?
sobes.tech AI
Answer from AI
The equals() method in the base class Object is intended for comparing objects for equality. By default, it compares references, meaning it returns true if both variables point to the same object in memory.
Often, in their classes, developers override equals() to compare objects based on the values of their fields rather than their references. This is important for the correct functioning of collections such as HashSet or HashMap.
Example of overriding equals():
@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;
}