Sobes.tech
Junior — Middle

How to choose the appropriate class to use as a key in HashMap to ensure data uniqueness and integrity?

sobes.tech AI

Answer from AI

To use a class as a key in a HashMap in Java, it is important to ensure the correct implementation of the hashCode() and equals() methods. This guarantees that keys are unique and compared correctly.

Main recommendations:

  • Override equals() to compare all fields that define the uniqueness of the object.
  • Override hashCode() in accordance with equals(), so that objects considered equal have the same hash code.
  • Key fields should be immutable to avoid issues with changing the key after placing it in a HashMap.

Example:

public class Person {
    private final String passportNumber;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return passportNumber.equals(person.passportNumber);
    }

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

Thus, Person objects with the same passportNumber will be considered the same keys in a HashMap.

How to choose the appropriate class to use as a key… - sobes.tech