Skip to lesson

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

WrongKeyTypeDemo.javaJava
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'));    }}
Output
get(1001):  null
get(1001L): Riya
containsKey(1002): false
get("A"): null, get('A'): 12

What this code does

  • get(1001) compiles because get takes any Object. Java boxes 1001 into an Integer, which never equals the Long key 1001L, so the answer is null.
  • The same trap catches Character keys: "A" is a String, not the char '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:

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

MapOfDemo.javaJava
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));    }}
Output
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.of gives a fixed map: any put throws, and a repeated key is refused as soon as the map is created.
  • new HashMap<>(catalog) makes a normal, changeable copy. Wrapping it in new TreeMap<>(…) prints it in A-Z order on every run, while Map.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 5

Trace 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

TrainChartDemo.javaJava
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"));    }}
Output
Confirmed: 5
  B2: 2 booked
  S4: 2 booked
  S5: 1 booked
Waiting: {B2=[Gita], S4=[Arjun]}
S4-32 is Riya
S5-2 is free

What this code does

  • A record key Seat makes equal seats one key, so putIfAbsent refuses Arjun and Gita, who asked for seats already taken.
  • merge counts confirmed seats per coach; computeIfAbsent groups the waiting passengers by coach. Both are TreeMaps, so coaches print in order.
  • getOrDefault with a fresh Seat object answers "who is in this seat?" without any null check.

Trace the code

Trace putIfAbsent with a record key

import java.util.HashMap;
import java.util.Map;
public class SeatTrace {
record Seat(String coach, int number) { }
public static void main(String[] args) {
Map<Seat, String> booked = new HashMap<>();
String[] names = {"Riya", "Kabir", "Meera"};
int[] seats = {32, 32, 33};
for (int i = 0; i < names.length; i++) {
String taken = booked.putIfAbsent(new Seat("S4", seats[i]), names[i]);
if (taken == null) {
System.out.println(names[i] + " booked S4-" + seats[i]);
} else {
System.out.println(names[i] + ": S4-" + seats[i] + " taken by " + taken);
}
}
System.out.println("Bookings: " + booked.size());
}
}

Variables

size
0

Output

(nothing printed yet)

Line 8An empty map; its keys are Seat records.

Step 1 of 8

Choosing the map

Ask what you need besides lookup by key, and pick the simplest map that gives it:

Java
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-order LinkedHashMap.
  • Sorted keys, ranges, next or previous key → TreeMap.
  • Fixed data that never changes → Map.of (copy into a TreeMap to print it in order).

Finish up

Mark complete & continue

Next: Must-do problems: Maps