Java Hashmap – Please explain how hash maps work


I am currently preparing for interviews, Java in particular.

A common question is to explain hash maps.

Every explanation says that in case there is more than a single value per key, the values are being linked listed to the bucket.

Now, in HashMap class, when we use put(), and the key is already in the map, the value is not being linked to the existing one (at list as I understand) but replacing it:

Map<String, Integer> map = new HashMap();
map.put("a", 1);
//map now have the pair ["a", 1]
map.put("a", 2);
//map now have the pair ["a", 2]
//And according to all hash maps tutorials, it should have been like: ["a", 1->2]

From the docs:

If the map previously contained a mapping for the key, the old value is replaced.

What am I missing here? I am a little confused…



You’re confusing the behaviour of a Map with the implementation of a HashMap.

In a Map, there is only one value for a key — if you put a new value for the same key, the old value will be replaced.

HashMaps are implemented using ‘buckets’ — an array of cells of finite size, indexed by the hashCode of the key.

It’s possible for two different keys to hash to the same bucket, a ‘hash collision’. In case of a collision, one solution is to put the (key, value) pairs into a list, which is searched when getting a value from that bucket. This list is part of the internal implementation of the HashMap and is not visible to the user of the HashMap.

This is probably what you are thinking of.

Source: stackoverflow