Junior — Middle
What parameters or conditions must be ensured for using an object of a class as a key in collections?
sobes.tech AI
Answer from AI
To use an object of a class as a key in collections like HashMap or HashSet, you need to ensure proper implementation of the equals() and hashCode() methods.
- The
equals()method should correctly compare objects by their logical equality, so that two logically equal objects are considered equal. - The
hashCode()method should return the same value for objects that are equal according toequals(). This is important for the correct distribution of keys in hash tables.
If these methods are not overridden, the default implementation from Object is used, which compares objects by reference, which can lead to incorrect collection behavior.
Example:
public class Person {
private String name;
private int id;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, id);
}
}