Command Palette

Search for a command to run...

Back to the lesson: Topic 9.4 — HashMap Internals
Core Java · Example 2 of 5

Why HashMap spreads the hash

The mask only looks at the low bits. Spreading copies information from the high bits down so it isn't thrown away.

A HashMap is an array of buckets. It turns each key's hashCode into a bucket index (after mixing the high bits into the low ones), keeps colliding entries in a linked list that becomes a red-black tree past 8 nodes (Java 8+), and doubles the array when it's 75% full, giving O(1) expected get and put.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Implement a tiny IntMap (keys and values are int) using separate chaining: an array of 8 bucket lists, index Math.floorMod(key, buckets.length), and put/get that replace or append. Put keys 1, 9 and 17 (which collide) and 2, then print get(9), get(17), get(3) and the length of bucket 1.

02

Count how many times each character appears in "mississippi" using a HashMap<Character, Integer> and merge, then print it as a TreeMap.

03

Two-sum with a map: given int[] nums = {2, 7, 11, 15} and target 9, return the indexes of two numbers that add up to the target in one pass. Print them.

Explain it without notes

01

Walk through exactly what happens in map.put(key, value) on a Java 8+ HashMap.

02

Why is the table length always a power of two, and what does h ^ (h >>> 16) achieve?

03

What are load factor and threshold, and what does a resize do in Java 8?

04

What is treeification, when does it happen, and why was it added?

05

Why must keys implement hashCode consistently with equals, and why should they be immutable?

Why HashMap spreads the hash
Sign in to run this example in your browser.

Expected output

without spreading: 1 bucket(s) used, biggest holds 16
with spreading:    16 buckets used, one key each