Junior — Middle
Is it necessary to keep objects identical after changing their properties if the equals method is used?
sobes.tech AI
Answer from AI
The equals method in Java is intended for comparing objects for logical equality, not for checking their identity or immutability. If the properties of an object change, the result of equals may change if those properties are considered in the equals method.
Is it necessary to keep objects equal after their properties change? No, it is not necessary. But if an object is used, for example, as a key in collections like HashMap or HashSet, then changing properties involved in equals and hashCode can lead to incorrect behavior of the collection.
Therefore:
- If an object changes, and these changes affect equals/hashCode, caution should be exercised when using such objects in collections.
- Ideally, objects used as keys should be immutable or should not change fields involved in equals/hashCode.
Example:
class Person {
private String id;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
return id.equals(person.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
// getters and setters
}
If the id is changed after placing the object in a HashSet, searching for this object in the set may not work.