Sobes.tech
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:

  1. Properly implemented hashCode() and equals() methods — so that HashMap can correctly compute the hash and compare keys to determine uniqueness.

  2. Immutability (preferably) — the key should not change its fields involved in the calculation of hashCode() and equals() 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.