Command Palette

Search for a command to run...

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

The two key bugs: mutable keys and equals without hashCode

The badge's entry is still in the map but unreachable by lookup. In theory the Ticket keys could share a bucket by chance; with identity hash codes they practically never do.

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?

The two key bugs: mutable keys and equals without hashCode
Sign in to run this example in your browser.

Expected output

size: 1
get(same object): null
get(new Badge("asha")): null
tickets stored: 2
equal? true