Command Palette

Search for a command to run...

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

From key to bucket, step by step

String.hashCode is part of the Java specification, so these numbers are the same on every JVM.

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?

From key to bucket, step by step
Sign in to run this example in your browser.

Expected output

apple  hashCode=93029210  spread=93030097  bucket=1
mango  hashCode=103662530 spread=103663087 bucket=15
tea    hashCode=114704    spread=114705    bucket=1
Aa     hashCode=2112      spread=2112      bucket=0
BB     hashCode=2112      spread=2112      bucket=0
Aa and BB collide: true
null key always goes to bucket 0