Sobes.tech
Junior

What requirements must objects of a class meet to be used as keys in a HashMap?

sobes.tech AI

Answer from AI

For an object of a class to be used as a key in a HashMap, it must satisfy the following requirements:

  1. Defined a hash function (hashCode in Java) — the object must return a correct and stable hash code that does not change during its use in a HashMap.

  2. Defined an equality comparison method (equals in Java) — objects considered equal must have the same hash code.

  3. Immutability of the key — the values of fields involved in calculating hashCode and equals should not change after placing the object in a HashMap, otherwise, it will lead to loss of access to the element.

Example in Java:

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 an object can be safely used as a key in a HashMap.