Sobes.tech
Junior — Middle

How can you guarantee the uniqueness of keys when using a HashMap data structure?

sobes.tech AI

Answer from AI

In Java, the HashMap data structure guarantees the uniqueness of keys by using the hashCode() and equals() methods of the key objects. When adding a key-value pair, HashMap computes the hash code of the key to determine the bucket where the element will be stored. If a bucket already contains an element with the same hash code, the equals() method is called to check for key equality.

To ensure key uniqueness:

  • Properly override the hashCode() and equals() methods in the key class so that objects considered equal have the same hash code.
  • Avoid mutability of keys after placing them in the HashMap, as changing the state of a key can break the correctness of lookups.

Example:

class Key {
    private final int id;

    public Key(int id) {
        this.id = id;
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Key other = (Key) obj;
        return this.id == other.id;
    }
}

HashMap<Key, String> map = new HashMap<>();
map.put(new Key(1), "value1");
map.put(new Key(1), "value2"); // will overwrite the value for the key with id=1