Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most map bugs come from a few mistakes: reading a missing key, looking up with the wrong key type, trusting an order that is not promised, and changing a map or a key at the wrong time. Once you know them, maps become one of the most useful tools you have.
Mistakes and fixes at a glance
The cheapest bug is a lookup that quietly finds nothing. get, containsKey and remove accept any Object, so a wrong key type still compiles. Below, Long and Character keys are looked up the wrong way.
Example 1 · Mistake: the wrong key type
import java.util.HashMap;import java.util.Map;
public class WrongKeyTypeDemo { public static void main(String[] args) { Map<Long, String> accounts = new HashMap<>(); accounts.put(1001L, "Riya"); accounts.put(1002L, "Arjun");
System.out.println("get(1001): " + accounts.get(1001)); System.out.println("get(1001L): " + accounts.get(1001L)); System.out.println("containsKey(1002): " + accounts.containsKey(1002));
Map<Character, Integer> grades = new HashMap<>(); grades.put('A', 12); System.out.println("get(\"A\"): " + grades.get("A") + ", get('A'): " + grades.get('A')); }}get(1001): null
get(1001L): Riya
containsKey(1002): false
get("A"): null, get('A'): 12What this code does
get(1001)compiles becausegettakes anyObject. Java boxes 1001 into anInteger, which never equals theLongkey 1001L, so the answer isnull.- The same trap catches
Characterkeys:"A"is aString, not thechar'A'. Always look up with exactly the key type.
Note that getOrDefault only returns the default; it does not store it in the map. The most common mistakes, each with its cause and the fix:
nullfromint x = map.get(k)crashing → the key is missing and unboxingnullthrows → usegetOrDefault(k, 0)orcontainsKey. Review: HashMap: keys and values (opens in a new tab)get(101)finds nothing on aMap<Long, String>→ anIntegernever equals aLong→ look up with101L. See the example below.UnsupportedOperationExceptiononput→ the map came fromMap.of→ copy it into aHashMap. See the next section.ConcurrentModificationException→removeinside a for-each orforEachloop → useremoveIfon a view. Review: Looping through a map (opens in a new tab)putIfAbsent(k, new ArrayList<>()).add(x)throws →putIfAbsentreturnsnullfor a new key → usecomputeIfAbsent. Review: Counting and grouping (opens in a new tab)- An entry lost after a setter call → a key was changed after
put→ use immutable keys such as records. Review: Maps with your own objects (opens in a new tab) ClassCastException ... Comparablein aTreeMap→ the key class cannot be sorted → implementComparableor pass aComparator. Review: LinkedHashMap and TreeMap (opens in a new tab)
Map.of and order
Map.of(...) is quick, but the map it makes cannot change. Below, put on it throws, a repeated key is refused, and a changeable copy is printed in sorted order.
Example 2 · Mistake: treating Map.of like a normal map
import java.util.HashMap;import java.util.Map;import java.util.TreeMap;
public class MapOfDemo { public static void main(String[] args) { Map<String, Integer> catalog = Map.of("Pen", 10, "Eraser", 15, "Notebook", 40);
try { catalog.put("Stapler", 30); } catch (UnsupportedOperationException e) { System.out.println("put on Map.of -> UnsupportedOperationException"); }
try { Map<String, Integer> bad = Map.of("Pen", 10, "Pen", 12); } catch (IllegalArgumentException e) { System.out.println("duplicate key -> " + e.getMessage()); }
Map<String, Integer> editable = new HashMap<>(catalog); editable.put("Stapler", 30); System.out.println("Sorted copy: " + new TreeMap<>(editable)); }}put on Map.of -> UnsupportedOperationException
duplicate key -> duplicate key: Pen
Sorted copy: {Eraser=15, Notebook=40, Pen=10, Stapler=30}What this code does
Map.ofgives a fixed map: anyputthrows, and a repeated key is refused as soon as the map is created.new HashMap<>(catalog)makes a normal, changeable copy. Wrapping it innew TreeMap<>(…)prints it in A-Z order on every run, whileMap.of's own order may differ between runs.
Map.of also refuses null keys and values and takes at most 10 pairs; for more, use Map.ofEntries(Map.entry(...), ...). Its loop order is not promised and can change from one run to the next, so copy into a TreeMap or use a LinkedHashMap when order matters.
Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: is the key type exact, can this map change, is a loop removing from its own map, and can the key class be sorted?
Find the bug
Find the map bug
Tap the wrong line, then check the fix.
Look up an account by its number.
Round 1 of 5Trace before you guess
When a map call surprises you, trace it: follow the key, then the value that comes back. Below, three passengers ask for seats and the second asks for a seat that is already taken.
Example 3 · Full example: a train chart
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.TreeMap;
record Seat(String coach, int number) {}
public class TrainChartDemo { public static void main(String[] args) { String[] requests = { "Riya,S4,32", "Kabir,S4,33", "Meera,B2,14", "Arjun,S4,32", "Diya,B2,15", "Farhan,S5,1", "Gita,B2,14" };
Map<Seat, String> booked = new HashMap<>(); Map<String, Integer> perCoach = new TreeMap<>(); Map<String, List<String>> waiting = new TreeMap<>();
for (String r : requests) { String[] p = r.split(","); Seat seat = new Seat(p[1], Integer.parseInt(p[2])); String taken = booked.putIfAbsent(seat, p[0]); if (taken == null) { perCoach.merge(seat.coach(), 1, (a, b) -> a + b); } else { waiting.computeIfAbsent(seat.coach(), k -> new ArrayList<>()).add(p[0]); } }
System.out.println("Confirmed: " + booked.size()); perCoach.forEach((coach, n) -> System.out.println(" " + coach + ": " + n + " booked")); System.out.println("Waiting: " + waiting); System.out.println("S4-32 is " + booked.get(new Seat("S4", 32))); System.out.println("S5-2 is " + booked.getOrDefault(new Seat("S5", 2), "free")); }}Confirmed: 5
B2: 2 booked
S4: 2 booked
S5: 1 booked
Waiting: {B2=[Gita], S4=[Arjun]}
S4-32 is Riya
S5-2 is freeWhat this code does
- A record key
Seatmakes equal seats one key, soputIfAbsentrefuses Arjun and Gita, who asked for seats already taken. mergecounts confirmed seats per coach;computeIfAbsentgroups the waiting passengers by coach. Both areTreeMaps, so coaches print in order.getOrDefaultwith a freshSeatobject answers "who is in this seat?" without any null check.
Trace the code
Trace putIfAbsent with a record key
Variables
- size
- 0
Output
(nothing printed yet)Line 8An empty map; its keys are Seat records.
Choosing the map
Ask what you need besides lookup by key, and pick the simplest map that gives it:
Map<String, Integer> seats = Map.of("S2", 72, "B1", 64, "S1", 72); // fixed dataMap<String, Integer> lookup = new HashMap<>(seats); // only fast lookupSystem.out.println(new TreeMap<>(seats)); // {B1=64, S1=72, S2=72}- Only fast lookup →
HashMap. - Output in the order things were added →
LinkedHashMap; keep only the latest few → access-orderLinkedHashMap. - Sorted keys, ranges, next or previous key →
TreeMap. - Fixed data that never changes →
Map.of(copy into aTreeMapto print it in order).
Finish up
Mark complete & continue
Next: Must-do problems: Maps