Repaso
Español
Java CoreIntermediateJV-37

Explain how a HashMap works internally.

Answer

  • It keeps an array of buckets. For put(key, value) it computes key.hashCode(), spreads the bits, and picks index = hash % arraySize.
  • If the bucket is empty, the entry is stored. If not (a collision), entries are chained in a linked list; since Java 8, a long chain (8+) becomes a balanced tree for faster search.
  • get(key): find the bucket by hash, then use equals to find the exact key. That is why equals and hashCode must be consistent.
  • When the map is more than 75% full (load factor 0.75), the array doubles and entries are redistributed (rehash).
  • Average O(1) get and put, worst case O(log n). Not thread-safe; allows one null key.

Key terms

Practice this question in Repaso