Sobes.tech
Junior — Middle

Have you used the equals method in your projects for object comparison?

sobes.tech AI

Answer from AI

Yes, the equals method is often used to compare objects in Java to determine if they are equal in meaning rather than by reference. By default, the equals method compares references (i.e., checks if variables point to the same object), but it is often overridden to compare the contents of objects.

For example, if you have a Person class with fields name and age, you can override equals to consider two objects equal if these fields match:

@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);
}

This allows for correct comparison of objects in collections and other data structures.