How does HashMap work internally in Java?

A HashMap is an array of buckets. When you call put(key, value):

  1. Java calls key.hashCode() and spreads the bits of the hash.
  2. The bucket index is found from the hash and the array length (the default size is 16).
  3. If the bucket is empty, the entry is stored there. If not, Java walks the bucket and uses equals() to find the same key. If it finds one, the value is replaced, if not the new entry is added.
  4. When the number of entries goes above capacity x load factor (0.75), the array is doubled and the entries are moved (rehashing).
  5. When one bucket gets long (8 or more entries, and the table has 64 or more buckets), the linked list becomes a balanced tree, so the search stays fast.

So the keys need a good hashCode() and a matching equals(). Even with a very bad hash code the map still gives right answers, only slow:

import java.util.HashMap;
import java.util.Map;

public class Main {
    static class BadKey {
        final int id;
        BadKey(int id) { this.id = id; }
        @Override public int hashCode() { return 1; }                     // all keys in one bucket
        @Override public boolean equals(Object o) { return o instanceof BadKey b && b.id == id; }
    }

    public static void main(String[] args) {
        Map<BadKey, String> map = new HashMap<>();
        for (int i = 0; i < 1000; i++) {
            map.put(new BadKey(i), "value" + i);
        }
        System.out.println(map.size());
        System.out.println(map.get(new BadKey(777)));
    }
}
Output

1000
value777

See Java HashMap.


Learn more about the similar topics:
Tutorials
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?