Sobes.tech
Junior — Middle

What types of objects are recommended to be used as keys in HashMap to avoid their loss or incorrect behavior?

sobes.tech AI

Answer from AI

It is recommended to use objects with immutable state as keys in a HashMap to avoid issues with data loss or incorrect behavior. This is because HashMap uses the hashCode() and equals() methods to find and compare keys. If the state of a key object changes after being placed in the HashMap, its hash code may change, and the object may become inaccessible for lookup.

Most commonly, the following are used as keys:

  • Strings (String), as they are immutable.
  • Wrapper objects over primitives (Integer, Long, UUID, etc.), which are also immutable.
  • Custom classes with overridden hashCode() and equals(), where all fields involved in hash code calculation must be immutable.

Example:

public final class PersonKey {
    private final String passportNumber;

    public PersonKey(String passportNumber) {
        this.passportNumber = passportNumber;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PersonKey)) return false;
        PersonKey that = (PersonKey) o;
        return passportNumber.equals(that.passportNumber);
    }

    @Override
    public int hashCode() {
        return passportNumber.hashCode();
    }
}

Thus, keys should be immutable and correctly implement hashCode() and equals().

What types of objects are recommended to be used as… - sobes.tech