Junior — Middle
What characteristic should a key have to be used in a HashMap?
sobes.tech AI
Answer from AI
The key used in a HashMap should have the following characteristics:
-
Properly implemented
hashCode()andequals()methods — so that HashMap can correctly compute the hash and compare keys to determine uniqueness. -
Immutability (preferably) — the key should not change its fields involved in the calculation of
hashCode()andequals()while it is used in the HashMap. Otherwise, this will lead to data integrity issues and the inability to find the element.
Example:
class Person {
private final String id;
public Person(String id) {
this.id = id;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return id.equals(other.id);
}
}
Such a key can be safely used in a HashMap.