HashMap

Basic Java
≈ 2 min read

How HashMap finds a value

HashMap<K, V> is one of the most commonly used Map implementations. Its main idea is to turn a key into a hash and use that hash to quickly find the area where the required entry should be located.

Map<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");

System.out.println(capitals.get("Japan"));

On average, the main put(), get(), and remove() operations run in close to constant time. That is what makes HashMap a strong choice when the main task is fast key-based access.

hashCode and equals work together

When looking up a key, the map uses hashCode() to narrow down where to search, and then equals() to distinguish the required key from others. You already know the contract of these methods; here you can see why it matters in practice.

Two different keys may produce the same hash. This is called a collision and is not an error by itself: HashMap can store multiple such entries and distinguish them with equals(). Problems begin when the equality methods themselves are implemented inconsistently.

A key should not “move” after insertion

It is dangerous to change fields of a key that affect equals() and hashCode() while the key is stored in the map. After the change, the map may search for the object using a different hash and fail to find the entry where it was originally placed.

The best keys are stable. Strings, numbers, enums, and other immutable values are convenient precisely because their equality and hash do not change unexpectedly while they are stored in a HashMap.

Order is not guaranteed

HashMap does not promise to preserve insertion order. If order matters to program logic, you must not reconstruct it from how entries happened to print in one run. A different map implementation should be chosen for that requirement.