Junior — Middle
How is key matching in data structures or algorithms determined?
sobes.tech AI
Answer from AI
In Java, key matching in data structures such as HashMap or HashSet is determined using the hashCode() and equals() methods of the key object.
- First,
hashCode()is called to compute the hash code of the key to identify the bucket in the hash table. - If there are multiple elements in this bucket (collision), the
equals()method is called for each to check for actual key equality.
Therefore, for correct key operation, both methods hashCode() and equals() must be overridden so that objects with the same logical value have the same hash code and are considered equal.
Example:
class Person {
private String 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);
}
}