Junior — Middle
Have you ever implemented your own equals method in a class?
sobes.tech AI
Answer from AI
Yes, I have implemented a custom equals method in classes to correctly compare objects based on their content rather than references. For example, if I have a Person class with fields name and age, overriding equals allows me 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 person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
This is important for the correct functioning of collections like HashSet or HashMap, where object comparison affects storage and retrieval.