Junior — Middle
What is the purpose of using the equals() method in programming?
sobes.tech AI
Answer from AI
The equals() method in programming, especially in Java, is used to compare objects for logical equality, not just reference equality in memory.
By default, the equals() method from the Object class compares references (i.e., checks if two variables point to the same object). However, it is often necessary to compare the contents of objects, such as the values of fields.
To do this, classes override the equals() method to define when two objects are considered equal in meaning.
Example:
class Person {
String name;
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 && name.equals(other.name);
}
}
Thus, equals() allows comparing objects by content, which is important for collections, searching, deletion, and other operations.