ExerciseWarm-up
Warm-up
The iteration order that lies to you
5 minfresher0–3 yrs
One concept, guided. Near-impossible to fail.
What this teaches
- HashMap guarantees no iteration order, ever
- Stable-looking output is a coincidence of hash distribution, not a promise
- LinkedHashMap for insertion order, TreeMap for sorted
Starter
Starter.java
import java.util.*;
/**
* WARM-UP — 5 minutes. One concept. Hard to fail.
*
* A report needs categories printed in the order they were added.
* This code does not do that reliably.
*
* TASKS
* 1. Predict the output before running.
* 2. Run it. Was your prediction right? (Most people get this one wrong
* for the right reason and right for the wrong reason.)
* 3. Change ONE word so insertion order is guaranteed.
* 4. Then change it so the keys come out alphabetically instead.
*/
public class Starter {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("zebra", 4);
stock.put("apple", 12);
stock.put("mango", 7);
stock.put("banana", 3);
stock.put("cherry", 19);
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
// Question to answer in a comment before you move on:
// HashMap makes NO ordering guarantee. So why does the output
// look stable every single time you run this?
}
}Run it locally:
cd exercises/java/collections/hashmap-internals/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out StarterDone when
- Output is guaranteed to be in insertion order
- A second version prints keys alphabetically