Collections Framework

The largest share of a paper.

8 lessons · 32 past questions · 166 marks in the papers collected here

Open the interactive lessons →Collections Framework past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Which container?
  2. Three map orders
  3. Totals: getOrDefault and merge
  4. Sets, sameness and order
  5. Removing while walking
  6. List iterators: edit while walking
  7. Stacks, queues and deques
  8. Loops that look or remove

1. Which container?

Different questions about data need different containers.

the four main shapes of collection and what a loop hands you from each

A weather station keeps three kinds of data. Readings arrive in time order and may repeat. Station codes must never repeat. Each region has its own list of readings, found by the region's name. One container cannot serve all three well.

Think of office furniture. A numbered rack keeps papers in order. A guest list holds each name once. A filing cabinet finds a folder by its label. A waiting line serves from its ends. The picture stops at size: Java containers grow by themselves.

Four questions, four interfaces

You need toInterfaceUsual classes
keep positions, allow repeatsListArrayList, LinkedList
hold each value onceSetHashSet, LinkedHashSet, TreeSet
look a value up by a keyMapHashMap, LinkedHashMap, TreeMap
add and remove at the endsDequeArrayDeque, LinkedList

Why two names on one line? In List<Integer> rain = new ArrayList<>(); the left side says what you may call. The right side chooses how it is stored. The empty <> copies the type argument from the left. Code written against List keeps working if you switch the class.

The element rule of for-each

In for (T x : things), T must be able to receive one element of things. For a List<Integer>, T may be Integer or int. A Map is not walked directly: choose keySet(), values() or entrySet().

Worked example: Adding up boxed numbers

Problem.

The list holds Integer objects. The loop variable is an int. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> rain = new ArrayList<>();
        rain.add(12);
        rain.add(7);
        rain.add(30);
        int total = 0;
        for (int mm : rain) {
            total += mm;
        }
        System.out.println("total " + total);
        System.out.println("average " + total / rain.size());
    }
}

What is asked.

Two lines.

Idea.

Each element is unboxed into mm. Both operands of the division are whole numbers.

  1. The list receives 12, 7 and 30.
  2. Each turn unboxes one element into mm and adds it to total, giving 12, 19, 49.
  3. total / rain.size() is 49 / 3 with two int values, so the fraction is dropped.

Answer.

total 49, then average 16

Common mistake.

Writing 16.33. Division of two int values never keeps a fraction.

What if

The rain program prints total 49 and average 16.

  • The loop header becomes for (Long mm : rain), and total still receives mm. Does it compile?
    It does not compile.. An Integer element is not a Long. Integer and Long never convert into each other.
  • The loop header becomes for (Integer mm : rain). What prints?
    The output is unchanged: total 49, average 16.. total += mm unboxes the Integer for the addition.
  • The last line divides (double) total / rain.size(). Is the average still 16?
    No: the second line prints a fraction that starts average 16.33.. One double operand makes the whole division keep its fraction.

Containers can sit inside containers. A map's value can itself be a list. The map holds only a reference to that list, so there is one list however you reach it. Step through the picture.

A map of lists

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, List<Integer>> temps = new TreeMap<>();
        temps.put("east", new ArrayList<>(List.of(18, 21)));
        temps.put("west", new ArrayList<>(List.of(15)));
        List<Integer> view = temps.get("east");
        view.add(24);
        System.out.println(temps);
        view = temps.get("west");
        System.out.println(view.size() + " " + temps.get("east").size());
    }
}

One list, two ways to reach it

  1. The map stores two arrows, one per key. Each list is its own object on the heap.
  2. get("east") hands back the arrow, so view reaches the very same list. Nothing was copied.
  3. view.add(24) changes that one list. The map sees the new value when printed.
  4. Assigning view again only moves the arrow. The east list keeps all three values.

Worked example: Walking a map of lists

Problem.

Each club maps to a list of member names. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, List<String>> clubs = new TreeMap<>();
        clubs.put("rowing", List.of("Ivo", "Perpetua"));
        clubs.put("chess", List.of("Bartholomew", "Ng", "Oyelaran"));
        String longest = "";
        for (List<String> members : clubs.values()) {
            for (String name : members) {
                if (name.length() > longest.length()) {
                    longest = name;
                }
            }
        }
        System.out.println(longest + " of " + clubs.size() + " clubs");
    }
}

What is asked.

One line.

Idea.

Peel one layer per loop: each value is a List<String>, and each element of that is a String.

  1. values() gives one list per club.
  2. The first name longer than the empty text is kept, and only a longer one replaces it.
  3. The lengths include Bartholomew with 11 letters; no other name is as long.
  4. size() of the map counts clubs, not people: 2.

Answer.

Bartholomew of 2 clubs

Common mistake.

Writing the inner loop as for (List<String> name : members). One element of a list of strings is one string.

Remove by position or by value

An int argument

List<Integer> lanes = new ArrayList<>(List.of(2, 0, 1));
lanes.remove(1);

An Integer argument

List<Integer> lanes = new ArrayList<>(List.of(2, 0, 1));
lanes.remove(Integer.valueOf(1));

The difference. The argument's type: int against Integer.

A list has remove(int index) and remove(Object value). An int picks the position; an object picks the first equal element. Here the left leaves [2, 1] and the right [2, 0].

When this breaks

The loop variable of a for-each holds a copy of the element's value or reference. Assigning to it changes the variable only, so the collection keeps its old contents.

Doubling that does nothing

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> fares = new ArrayList<>(List.of(30, 45));
        for (int fare : fares) {
            fare = fare * 2;
        }
        System.out.println(fares);
    }
}

2. Three map orders

The class you build decides the order you see.

the order in which HashMap, LinkedHashMap and TreeMap hand back their keys

A bus depot records minutes until each route arrives. The driver's board must list routes as they were reported. The public index must list them alphabetically. The data is the same. Only the container differs.

Picture three secretaries. One throws each card into whichever drawer a code picks, and never promises how you will meet the cards again. One does the same but also ties a thread from each card to the next one that arrived. One files every card in sorted position at once.

The three maps

ClassIteration ordernull key
HashMapunspecified: no promise at allone allowed
LinkedHashMaporder of first insertionone allowed
TreeMapkeys sorted in natural orderrejected

Why three? Keeping an order costs memory or time. A hash map keeps none. A linked map keeps the thread, which costs two extra arrows per entry. A tree map compares keys on every insertion so that walking it is already sorted.

One order everywhere

A map's order applies to printing, to keySet(), to values() and to entrySet() alike. Printing a map shows {key=value, key=value}.

The depot

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> arrival = new LinkedHashMap<>();
        Map<String, Integer> sorted = new TreeMap<>();
        String[] routes = {"M7", "C2", "K9", "C2"};
        int[] minutes = {4, 11, 6, 3};
        for (int i = 0; i < routes.length; i++) {
            arrival.put(routes[i], minutes[i]);
            sorted.put(routes[i], minutes[i]);
        }
        System.out.println(arrival);
        System.out.println(sorted);
    }
}

Same puts, two orders

  1. The first put: both maps hold one pair.
  2. C2 joins the end of the linked map, but moves to the front of the tree map because C comes before M.
  3. K9 goes last in arrival order, and between C and M in sorted order.
  4. C2 again: the value is replaced. The key keeps its place in both maps.

Worked example: Keys, values, and what put returns

Problem.

A TreeMap with number keys receives key 30 twice. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        var locker = new TreeMap<Integer, String>();
        locker.put(30, "Zed");
        locker.put(4, "Ama");
        String old = locker.put(30, "Lin");
        System.out.println(old);
        System.out.println(locker.keySet() + " " + locker.values());
        for (Map.Entry<Integer, String> e : locker.entrySet()) {
            System.out.println(e.getKey() + ":" + e.getValue());
        }
    }
}

What is asked.

Four lines.

Idea.

put returns the value that the key had before, or null for a new key.

  1. Key 30 gets Zed, then key 4 gets Ama.
  2. The third put replaces Zed with Lin and returns Zed.
  3. Numbers sort by size, so 4 comes before 30 in both keySet() and values().
  4. The entrySet() loop visits the same order.

Answer.

Zed, then [4, 30] [Ama, Lin], then 4:Ama, 30:Lin

Common mistake.

Expecting two entries for key 30, or values sorted by their own text.

Worked example: A sorted copy that changes alone

Problem.

A TreeMap is built from a HashMap, then changed. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> seen = new HashMap<>();
        seen.put("heron", 2);
        seen.put("wren", 9);
        seen.put("owl", 1);
        Map<String, Integer> index = new TreeMap<>(seen);
        index.remove("owl");
        index.put("kite", 4);
        System.out.println(index);
        System.out.println(index.containsKey("owl") + " " + seen.containsKey("owl"));
    }
}

What is asked.

Two lines.

Idea.

The copy takes the entries and sorts them. After that the two maps are separate.

  1. index starts with the three entries of seen, sorted by key: heron, owl, wren.
  2. remove("owl") changes index only.
  3. put("kite", 4) adds a key that sorts between heron and wren.
  4. index no longer has owl, but seen still does.

Answer.

{heron=2, kite=4, wren=9}, then false true

Common mistake.

Believing that a removal from the copy also removes from the source.

What if

The copy program prints {heron=2, kite=4, wren=9} and then false true.

  • The line index.remove("owl"); is deleted. What prints?
    It prints {heron=2, kite=4, owl=1, wren=9}, then true true.. owl is still in the copy, and it sorts between kite and wren.
  • The put becomes index.put("wren", 0); What prints?
    It prints {heron=2, wren=0}, then false true.. wren already exists, so its value is replaced and no key is added.

Arrival or sorted

LinkedHashMap

var m = new LinkedHashMap<String, Integer>();
m.put("yak", 1);
m.put("ant", 2);
System.out.println(m);

TreeMap

var m = new TreeMap<String, Integer>();
m.put("yak", 1);
m.put("ant", 2);
System.out.println(m);

The difference. The class after new.

The linked map shows yak first because it arrived first. The tree map shows ant first because it sorts first.

When this breaks

"Sorted" means the type's natural order, not dictionary order. For strings, digits come before capital letters, and capitals before small letters. Text such as "10" sorts before "9" because the first characters are compared.

Natural order of text

import java.util.*;
public class Main {
    public static void main(String[] args) {
        var words = new TreeMap<String, Integer>();
        words.put("apt", 1);
        words.put("Zulu", 2);
        words.put("10", 3);
        words.put("9", 4);
        System.out.println(words.keySet());
    }
}

3. Totals: getOrDefault and merge

The first value for a key and later values need different handling.

two ways to build a running total, count or best value per key

A parcel office adds up kilograms per courier as parcels come in. For a courier seen before, add to the old total. For a new courier there is no old total, and get answers null.

Think of a ledger. Before you write a new balance, you look for the old one. If the page is blank, you pretend it says zero. getOrDefault is that pretence: it reads, but writes nothing.

Why not just get? get returns null for a missing key. Adding 1 to a null Integer forces Java to unbox null, which throws NullPointerException.

getOrDefault

m.getOrDefault(key, d) returns the value stored for key, or d if the map has no entry for the key. It never changes the map. Both arguments are required.

Worked example: Count the letters

Problem.

What does this print?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<Character, Integer> tally = new LinkedHashMap<>();
        for (char c : "bobbin".toCharArray()) {
            tally.put(c, tally.getOrDefault(c, 0) + 1);
        }
        System.out.println(tally);
    }
}

What is asked.

The map after the loop.

Idea.

Each turn reads the old count (or 0), adds one, and writes it back.

  1. b: missing, so 0 + 1 = 1.
  2. o: missing, so 1.
  3. b again: old 1, new 2. Then b once more: 3.
  4. i and n are new, each 1.
  5. The map is linked, so keys keep the order of their first appearance.

Answer.

{b=3, o=1, i=1, n=1}

Common mistake.

Listing the keys alphabetically, or listing b three times.

Java offers the whole pattern as one call. merge(key, value, function) says: store value if the key has none; otherwise combine the old value with value.

The merge rule
  1. No value for the key (or a stored null): store the given value. The function does not run. 2. A value exists: call function(oldValue, givenValue) and store its result. 3. If that result is null: remove the key. The given value itself must not be null.

Parcels

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> kilos = new LinkedHashMap<>();
        kilos.merge("van", 40, (old, extra) -> old + extra);
        kilos.merge("bike", 6, (old, extra) -> old + extra);
        kilos.merge("van", 25, (old, extra) -> old + extra);
        System.out.println(kilos);
    }
}

merge, call by call

  1. van is missing, so merge stores 40 as it is. The lambda is not run.
  2. bike is also new. Again the value is stored directly.
  3. van exists. The lambda receives the stored value first and the new value second.
  4. The result, 65, replaces the old value. The key keeps its first place.

Worked example: Sales that can empty a shelf

Problem.

Each merge records units sold. The second function may answer null. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> shelf = new TreeMap<>();
        shelf.put("glue", 8);
        shelf.put("tape", 3);
        shelf.merge("glue", 5, (have, sold) -> have - sold);
        shelf.merge("tape", 3, (have, sold) -> have.equals(sold) ? null : have - sold);
        shelf.merge("pins", 7, (have, sold) -> have - sold);
        System.out.println(shelf);
    }
}

What is asked.

The final map.

Idea.

Apply the three cases of the rule to each call.

  1. glue has 8, so the function runs: 8 - 5 stores 3.
  2. tape has 3 and 3 are sold. have.equals(sold) is true, so the function answers null and tape is removed.
  3. pins has no value, so 7 is stored directly. The function does not run, although it is a subtraction.
  4. The tree map prints in key order.

Answer.

{glue=3, pins=7}

Common mistake.

Writing pins=-7. A new key stores the given value as it is.

What if

The shelf program prints {glue=3, pins=7}.

  • The first function becomes (have, sold) -> sold - have. What happens to glue?
    It prints {glue=-3, pins=7}.. The parameters keep their meaning by position: the first receives the old value 8, the second the new value 5.
  • The glue call becomes shelf.put("glue", 5); What prints?
    It prints {glue=5, pins=7}.. put ignores the old value completely.
  • The pins call is made twice. What is the value of pins?
    It prints {glue=3, pins=0}.. The second call finds 7, runs 7 - 7 and stores 0. A result of 0 is a value, not null.

Worked example: Joining text

Problem.

The values are strings. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, String> log = new TreeMap<>();
        String[][] events = {{"gate", "open"}, {"pump", "on"}, {"gate", "shut"}};
        for (String[] e : events) {
            log.merge(e[0], e[1], (before, now) -> before + ">" + now);
        }
        System.out.println(log);
    }
}

What is asked.

The final map.

Idea.

Order of the two parameters now shows in the output.

  1. gate is new: stores open.
  2. pump is new: stores on.
  3. gate exists: the function builds open>shut.
  4. The tree map prints gate before pump.

Answer.

{gate=open>shut, pump=on}

Common mistake.

Writing shut>open. The old value is the first parameter.

Replace or combine

put

The old value is lost.

hits.put("home", 1);

merge

The old value takes part.

hits.merge("home", 1, Integer::sum);

The difference. merge has a third argument that combines old and new.

Integer::sum is the same function as (a, b) -> a + b. Math::max and Math::min keep the larger or smaller value.

When this breaks

getOrDefault uses the default only when the key is absent. If the key is present with the value null, it returns null. merge, in contrast, treats a stored null like no value.

A stored null

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<String, Integer> seats = new HashMap<>();
        seats.put("A", null);
        System.out.println(seats.getOrDefault("A", 50));
        System.out.println(seats.getOrDefault("B", 50));
        seats.merge("A", 2, (x, y) -> x * y);
        System.out.println(seats.get("A"));
    }
}

4. Sets, sameness and order

A set answers one question: is this value already here?

how the three sets refuse repeats and in which order they show what remains

A lab door logs badge numbers. People swipe more than once, but the report must name each person once. One report keeps the order of first arrival; another is sorted.

A set is a guest list with a strict doorman. Before writing a name, the doorman asks whether it is already there. The difference between the three sets is how the doorman searches and how the list reads afterwards. The picture stops at identity: the doorman compares by your class's rules, not by face.

The three sets

ClassOrder when walkedHow a repeat is detected
HashSetunspecifiedhashCode, then equals
LinkedHashSetorder of first insertionhashCode, then equals
TreeSetsorted in natural ordercomparing for order: 0 means the same
add reports

add(x) returns true if the set changed and false if an equal element was already present. A refused repeat does not move the first copy.

Worked example: The sign-in sheet

Problem.

Some ids swipe more than once. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Set<String> seen = new LinkedHashSet<>();
        Set<String> repeated = new TreeSet<>();
        for (String id : new String[]{"R12", "B40", "R12", "A07", "B40", "R12"}) {
            if (!seen.add(id)) {
                repeated.add(id);
            }
        }
        System.out.println(repeated);
        System.out.println(seen.remove("R12") + " " + seen.remove("Z99"));
        seen.add("R12");
        System.out.println(seen);
    }
}

What is asked.

Three lines.

Idea.

add answers false for a repeat. remove answers whether something was there.

  1. R12, B40 and A07 are each accepted the first time.
  2. The repeats are R12, B40 and R12; the tree set holds each once, sorted: B40, R12.
  3. seen.remove("R12") is true; seen.remove("Z99") is false.
  4. Adding R12 again puts it at the end of the linked order.

Answer.

[B40, R12], true false, [B40, A07, R12]

Common mistake.

Putting R12 back in its old first place.

Why does a hash set need a number? Searching every element for a repeat would be slow. A hash set first computes a number from the element and uses it to jump to one bucket. Only the elements there are compared with equals. The next picture is a model with four buckets. Real hash sets pick buckets by their own formula.

Stamps that know when they are equal

import java.util.*;
class Stamp {
    private final int code;
    Stamp(int code) { this.code = code; }
    @Override
    public boolean equals(Object o) {
        return o instanceof Stamp && ((Stamp) o).code == code;
    }
    @Override
    public int hashCode() { return code; }
}
public class Main {
    public static void main(String[] args) {
        Set<Stamp> album = new HashSet<>();
        System.out.println(album.add(new Stamp(6)));
        System.out.println(album.add(new Stamp(9)));
        System.out.println(album.add(new Stamp(6)));
        System.out.println(album.size() + " " + album.contains(new Stamp(9)));
    }
}

A model of hash buckets

  1. This model has four buckets and uses hashCode % 4. Code 6 leads to bucket 2, which is empty, so it is stored.
  2. Code 9 leads to bucket 1. Also empty, so a second element is stored.
  3. A new Stamp(6): only bucket 2 is searched. equals says it matches, so add returns false.
  4. contains(new Stamp(9)) goes straight to bucket 1 and finds an equal element.
The equals and hashCode contract

If a.equals(b) is true, then a.hashCode() and b.hashCode() must be the same number. The reverse is not required: unequal objects may share a code. A class that overrides equals must override hashCode to match.

equals without hashCode

  1. equals calls the two stamps equal, but the inherited hashCode knows nothing about code.
  2. The two codes are almost always different. Then the set does not match the first stamp and stores a second one.
  3. Add hashCode returning code: equal stamps share a bucket, equals is asked, and the second is refused.
What if

The stamp program prints true, true, false, 2 true.

  • hashCode returns 1 for every stamp. What prints?
    The same four lines print: true, true, false, 2 true.. The contract still holds. All stamps share a bucket, so equals does all the work.
  • The hashCode method is deleted. What is the third line?
    On this run it prints true, and the last line starts with 3.. Equal stamps now report unrelated codes. The contract is broken, so the set cannot be relied on to see them as equal.
  • album is built as new TreeSet<>() and nothing else changes. What happens at the first add?
    It compiles and then throws ClassCastException.. A tree set must compare elements for order, and Stamp offers no such comparison.
Hash order

HashSet documentation says it makes no guarantee about iteration order, nor that the order stays the same over time. A question that asks what a hash set walk always prints has no fixed line to give.

Worked example: Grouping by length

Problem.

Words are grouped by how many letters they have. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Map<Integer, Set<String>> byLength = new TreeMap<>();
        for (String word : "saw nails brush hinge saw".split(" ")) {
            if (!byLength.containsKey(word.length())) {
                byLength.put(word.length(), new TreeSet<>());
            }
            byLength.get(word.length()).add(word);
        }
        System.out.println(byLength);
    }
}

What is asked.

One line.

Idea.

The map sorts the lengths, and each tree set sorts its own words.

  1. saw has 3 letters, so key 3 gets a new set holding saw.
  2. nails, brush and hinge all have 5 letters and share one set.
  3. The second saw finds its set and is refused as a repeat.
  4. Printing shows keys in order, and the words of each set in order.

Answer.

{3=[saw], 5=[brush, hinge, nails]}

Common mistake.

Listing saw twice, or keeping arrival order inside a set.

Worked example: What add and remove report

Problem.

A tree set is built from a list with repeats, then changed. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        TreeSet<Integer> distinct = new TreeSet<>(List.of(7, 2, 7, 11, 2));
        System.out.println(distinct.add(11) + " " + distinct.remove(7) + " " + distinct.add(7));
        System.out.println(distinct + " " + distinct.first() + " " + distinct.last());
    }
}

What is asked.

Two lines.

Idea.

Each call answers true only if the set changed.

  1. The set starts as 2, 7, 11.
  2. add(11) finds 11 already present: false.
  3. remove(7) deletes it: true.
  4. add(7) puts it back: true. The set is 2, 7, 11 again.

Answer.

false true true, then [2, 7, 11] 2 11

Common mistake.

Expecting add to answer true for a value that is already there.

Linked set or tree set

LinkedHashSet

Set<String> s = new LinkedHashSet<>();
s.add("pear");
s.add("date");

TreeSet

Set<String> s = new TreeSet<>();
s.add("pear");
s.add("date");

The difference. The class after new.

Printed order is arrival order for the linked set and sorted order for the tree set.

Linked set or plain hash set

LinkedHashSet

Set<String> s = new LinkedHashSet<>(words);

HashSet

Set<String> s = new HashSet<>(words);

The difference. The word Linked.

Only the linked set promises the source's order. The plain hash set promises none.

When this breaks

A tree set needs elements it can compare. String and Integer can compare themselves. A class of your own without that ability passes the compiler and fails when added.

No order to sort by

import java.util.*;
class Kite {
    int span;
    Kite(int span) { this.span = span; }
}
public class Main {
    public static void main(String[] args) {
        Set<Kite> loose = new HashSet<>();
        loose.add(new Kite(2));
        System.out.println(loose.size());
        Set<Kite> ranked = new TreeSet<>();
        ranked.add(new Kite(2));
        System.out.println(ranked.size());
    }
}

5. Removing while walking

An iterator is a bookmark that can delete what it just read.

the iterator behind every loop and its safe way to delete

A clinic screen lists waiting times. Anyone waiting over 60 minutes moves to another desk, so the screen must drop them while it walks down the list.

An iterator is your finger moving down a paper list. If someone else cuts a line out while your finger is on the page, you lose your place. If your hand strikes out the line you just read, you know where you are. The picture stops here: a real iterator moves one step back after a removal, so nothing is skipped.

Why only through the iterator? The iterator remembers a position number and how often the list has changed. Its own remove updates both. A change through the list updates only the list, and the mismatch is reported on a later next().

The iterator loop

Iterator<T> it = c.iterator(); then while (it.hasNext()) { T x = it.next(); if (drop) it.remove(); }. Call remove() with no argument, after next(), at most once per next().

Drop the long waits

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> waits = new ArrayList<>(List.of(4, 65, 90, 12));
        Iterator<Integer> walker = waits.iterator();
        while (walker.hasNext()) {
            int minutes = walker.next();
            if (minutes > 60) {
                walker.remove();
            }
        }
        System.out.println(waits);
    }
}

The cursor and a safe removal

  1. A fresh iterator points before the first element. Nothing has been returned yet.
  2. next() returns 4 and steps forward. 4 is not over 60, so it stays.
  3. next() returns 65, which must go.
  4. remove() deletes the last returned element and moves the cursor back by one, so 90 is not skipped.
  5. next() returns 90.
  6. 90 is removed in the same safe way.
  7. 12 is visited and kept. hasNext() is now false, so the loop ends.

Worked example: Remove from a fixed list

Problem.

The program calls remove() on a list built with List.of. What happens?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> doors = List.of("north", "south");
        Iterator<String> it = doors.iterator();
        System.out.println(it.next());
        it.remove();
        System.out.println(doors);
    }
}

What is asked.

Output and any exception.

Idea.

Ask what List.of builds: a list whose size is fixed.

  1. it.next() returns north, which prints.
  2. it.remove() tries to shrink the list.
  3. A list from List.of cannot change, so the call throws.
  4. The last line is never reached.

Answer.

north, then UnsupportedOperationException

Common mistake.

Calling this a compilation error. The call compiles, because Iterator declares remove.

What if

The waiting-list program prints [4, 12].

  • walker.remove(); is written twice in the if body. What happens?
    It throws IllegalStateException at the first time over 60.. The second call has no unremoved element: the one from next() is already gone.
  • The line int minutes = walker.next(); is replaced by int minutes = 99; What happens?
    It throws IllegalStateException on the first turn.. remove() was called before any next(), so there is nothing to delete.
  • The test becomes minutes < 60. What prints?
    It prints [65, 90].. The same machinery drops the short waits instead.

Worked example: Remove some, count others

Problem.

Papers starting with x- go. The other papers longer than three letters are counted. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> desk = new ArrayList<>(List.of("memo", "x-old", "invoice", "x-spam", "map"));
        int longer = 0;
        Iterator<String> it = desk.iterator();
        while (it.hasNext()) {
            String paper = it.next();
            if (paper.startsWith("x-")) {
                it.remove();
            } else if (paper.length() > 3) {
                longer++;
            }
        }
        System.out.println(desk);
        System.out.println(longer);
    }
}

What is asked.

Two lines.

Idea.

Judge each paper once. Removal changes the list; counting leaves it alone.

  1. memo: not x-, and 4 letters, so it is counted.
  2. x-old: removed.
  3. invoice: counted.
  4. x-spam: removed.
  5. map: 3 letters, neither removed nor counted.

Answer.

[memo, invoice, map], then 2

Common mistake.

Counting the removed papers too.

Who deletes?

The iterator

Safe during the walk.

String t = it.next();
it.remove();

The list

Changes the list behind the iterator.

String t = it.next();
tasks.remove(t);

The difference. The object that receives the call, and the argument.

During a walk, only the walking iterator may change the size of the collection.

The loud failure

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> crew = new ArrayList<>(List.of("Ada", "Bo", "Cyr", "Dee"));
        for (String name : crew) {
            System.out.println(name);
            if (name.equals("Ada")) {
                crew.remove(name);
            }
        }
        System.out.println(crew);
    }
}

Changing a list behind the loop

  1. A for-each loop builds an iterator that notes how many structural changes the list has had.
  2. The loop body gets Ada and prints it.
  3. crew.remove(name) goes around the iterator. The list counts a change; the iterator does not know.
  4. hasNext() says yes (1 is not the size 3). next() compares the counts and throws ConcurrentModificationException.
When this breaks

"Removing through the list always throws" is false. The check runs inside next() and the iterator's remove(), not inside hasNext(). If the loop ends before another next(), nothing is thrown. The documentation calls this detection best effort: never rely on it either way.

The silent skip

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> crew = new ArrayList<>(List.of("Ada", "Bo", "Cyr", "Dee"));
        for (String name : crew) {
            System.out.println(name);
            if (name.equals("Cyr")) {
                crew.remove(name);
            }
        }
        System.out.println(crew);
    }
}

6. List iterators: edit while walking

A list iterator can also go back, replace and insert.

the two-way iterator that lists offer, and what it may change

A timetable must get a rest period after every sports lesson, while you walk down it once. A plain iterator can only read and delete. You need a tool that can insert at your current place.

Picture a text cursor. It blinks between letters. Pressing the right arrow jumps over one letter. Typing inserts at the blink. Pressing delete removes the letter you just crossed. The picture stops at one point: after you type, the iterator refuses to delete or overwrite until it crosses another element.

Why a gap? An element position becomes unclear once you delete it. A gap stays meaningful: whatever you add or remove, "between these two neighbours" is still a place.

The editing calls

CallEffect
next() / previous()cross one element and return it
remove()delete the element last returned
set(x)overwrite the element last returned
add(x)insert at the cursor; the cursor ends up after it
nextIndex() / previousIndex()positions on either side of the cursor
The one-edit rule

set needs a next or previous with no add or remove since. remove also needs that, and cannot run twice. add may follow anything. Breaking the rule throws IllegalStateException.

Worked example: Back and forth

Problem.

A list [10, 20, 30] is walked. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        ListIterator<Integer> cur = new ArrayList<>(List.of(10, 20, 30)).listIterator();
        System.out.println(cur.next());
        System.out.println(cur.next());
        System.out.println(cur.previous());
        System.out.println(cur.next());
        System.out.println(cur.nextIndex() + " " + cur.previousIndex());
    }
}

What is asked.

Five lines.

Idea.

Move the cursor on paper: each call crosses one element.

  1. Two next() calls return 10 and 20. The cursor is after 20.
  2. previous() crosses 20 backwards and returns it.
  3. next() crosses it again: 20.
  4. The cursor sits between 20 and 30: next index 2, previous index 1.

Answer.

10, 20, 20, 20, 2 1

Common mistake.

Printing 10 for previous(), as if it returned the element before the last one returned.

The cursor lives between elements

  1. Gap 0 is before the first element.
  2. next() jumps over 10 and returns it.
  3. next() returns 20. The cursor is in gap 2.
  4. previous() jumps back over 20 and returns the same element again.
  5. One more next() returns 20 a third time.
  6. The last line prints the two index numbers around the gap: 2 and 1.

Number every track

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> tracks = new ArrayList<>(List.of("intro", "rain", "outro"));
        ListIterator<String> cur = tracks.listIterator();
        while (cur.hasNext()) {
            int at = cur.nextIndex();
            String t = cur.next();
            cur.set(at + "-" + t);
        }
        System.out.println(tracks);
    }
}
What if

The track program prints [0-intro, 1-rain, 2-outro].

  • cur.set(...) becomes cur.remove(); What prints?
    It prints [].. Each element is deleted right after it is returned.
  • cur is declared as Iterator<String> and built with tracks.iterator(), keeping the loop body. Does it compile?
    It does not compile.. Iterator has neither nextIndex nor set.
  • The line int at = cur.nextIndex(); moves below String t = cur.next(); What prints?
    It prints [1-intro, 2-rain, 3-outro].. After next() the gap has moved forward by one.

Worked example: Insert, then clean up backwards

Problem.

A rest is added after each gym, then a backward walk removes every rest. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> day = new LinkedList<>(List.of("maths", "gym", "art", "gym"));
        ListIterator<String> cur = day.listIterator();
        while (cur.hasNext()) {
            if (cur.next().equals("gym")) {
                cur.add("rest");
            }
        }
        System.out.println(day);
        while (cur.hasPrevious()) {
            String s = cur.previous();
            if (s.equals("rest")) {
                cur.remove();
            }
        }
        System.out.println(day);
        System.out.println(cur.nextIndex() + " " + cur.next());
    }
}

What is asked.

Three lines.

Idea.

add places the new item behind the cursor, so the forward walk never reads it.

  1. After the first gym, rest is inserted and the cursor is after it.
  2. The walk continues with art, then the second gym, followed by another insert.
  3. First print: [maths, gym, rest, art, gym, rest].
  4. Walking back, each rest is returned by previous() and removed.
  5. The cursor ends at the start: nextIndex() is 0 and next() gives maths.

Answer.

[maths, gym, rest, art, gym, rest], [maths, gym, art, gym], 0 maths

Common mistake.

Expecting the forward loop to meet the inserted rest and loop on it.

Two iterators

Iterator

Forward only; may remove.

Iterator<String> it = row.iterator();

ListIterator

Both ways; may remove, set and add. Lists only.

ListIterator<String> it = row.listIterator();

The difference. The type and the method that builds it.

Pick listIterator() when you must insert, replace or go back.

When this breaks

"I can always set the element I just read" is false once you have called add. The program compiles and then throws.

set after add

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> row = new ArrayList<>(List.of("a", "b"));
        ListIterator<String> cur = row.listIterator();
        cur.next();
        cur.add("new");
        System.out.println(row);
        cur.set("oops");
        System.out.println(row);
    }
}

7. Stacks, queues and deques

The order out depends on which end you use.

which end each call adds to and removes from

A copy shop has two containers. Print jobs must be done in the order they came. Undo steps must be undone newest first. Same items, opposite exits.

A queue is a line at a counter: join at the back, leave at the front. A stack is a pile of plates: add on top, take from the top. A deque is a corridor with a door at each end, so it can act as either. The pictures stop at peeking: Java lets you look at an end without taking the item.

Calls by end (Deque)

JobHeadTail
addaddFirst, offerFirst, pushaddLast, offerLast, add, offer
removepollFirst, poll, pop, remove, removeFirstpollLast, removeLast
lookpeekFirst, peek, element, getFirstpeekLast, getLast

Why so many names? Deque serves two older vocabularies at once. Queue words (add, offer, poll, peek) join at the tail and leave from the head. Stack words (push, pop, peek) use the head for both.

Two behaviours from one rule

Queue: add at the tail, poll from the head. Stack on a deque: push and pop, both at the head. The class Stack also has push, pop and peek, and treats the newest item as its top.

The copy shop

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Stack<String> undo = new Stack<>();
        Deque<String> print = new ArrayDeque<>();
        for (String job : new String[]{"cv", "form", "poster"}) {
            undo.push(job);
            print.add(job);
        }
        System.out.println(undo + " " + print);
        System.out.println(undo.pop() + " " + print.poll());
        System.out.println(undo.peek() + " " + print.peek());
        System.out.println(undo + " " + print);
    }
}

Same input, two exits

  1. The first job goes into both containers.
  2. Both print in the order added, yet their exits differ: a stack leaves from the newest end.
  3. pop() took the newest, poster. poll() took the oldest, cv.
  4. peek() only reads the next one to leave. Both containers are unchanged.

Worked example: Which pile is printed how?

Problem.

A Stack and an ArrayDeque both receive push(1), push(2), push(3). What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Stack<Integer> old = new Stack<>();
        Deque<Integer> modern = new ArrayDeque<>();
        for (int plate = 1; plate <= 3; plate++) {
            old.push(plate);
            modern.push(plate);
        }
        System.out.println(old);
        System.out.println(modern);
        System.out.println(old.peek() + " " + modern.peek());
    }
}

What is asked.

Three lines.

Idea.

Both use stack words, but they print from different ends.

  1. Stack prints from the bottom: the first pushed comes first.
  2. A deque prints from its head, and push puts each new item at the head.
  3. So the two lists look reversed.
  4. Both peek() calls show the newest item, 3.

Answer.

[1, 2, 3], then [3, 2, 1], then 3 3

Common mistake.

Assuming both print the same list because both are used as stacks.

What if

The copy shop prints poster cv on its second line.

  • The deque uses print.push(job) in place of print.add(job). What is the second line?
    It prints poster poster.. push puts each job at the head, so poll returns the newest: the deque now behaves as a stack.
  • print.poll() becomes print.pollLast(). What is the second line?
    It prints poster poster.. The tail holds the job added last.
  • The line print.add(job); becomes print.addFirst(job); and print.poll() becomes print.pollLast(). What is the second line?
    It prints poster cv.. Both ends were swapped, so the queue behaviour returns.

Worked example: Five ways in, four ways out

Problem.

A deque receives five names through five different calls. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<String> line = new ArrayDeque<>();
        line.add("Mia");
        line.addLast("Raj");
        line.push("Eve");
        line.addFirst("Kai");
        line.offer("Sol");
        System.out.println(line);
        System.out.println(line.pollFirst() + " " + line.pollLast());
        System.out.println(line.pop() + " " + line.peekLast());
        System.out.println(line);
    }
}

What is asked.

Four lines.

Idea.

Draw the row with the head on the left and place each name at the end its call uses.

  1. add and addLast: Mia Raj.
  2. push and addFirst use the head: Kai Eve Mia Raj.
  3. offer uses the tail: Sol goes last.
  4. pollFirst gives Kai, pollLast gives Sol.
  5. pop gives Eve; peekLast reads Raj without removing.

Answer.

[Kai, Eve, Mia, Raj, Sol], Kai Sol, Eve Raj, [Mia, Raj]

Common mistake.

Treating push like add. They use opposite ends.

Which end does each call use?

  1. add and addLast both join at the tail.
  2. push joins at the head, in front of everyone.
  3. addFirst also uses the head.
  4. offer is the queue's way to join the tail.
  5. pollFirst removed Kai from the head and pollLast removed Sol from the tail.
  6. pop removed Eve from the head. peekLast only read Raj.

push or add

push

Deque<String> d = new ArrayDeque<>();
d.push("a");
d.push("b");

add

Deque<String> d = new ArrayDeque<>();
d.add("a");
d.add("b");

The difference. The method name.

push builds the row backwards (b at the head); add builds it in arrival order.

When this breaks

"An empty container just answers null" holds for poll and peek only. pop on an empty deque throws NoSuchElementException, and pop or peek on an empty Stack throws EmptyStackException.

Empty tray

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<String> tray = new ArrayDeque<>();
        System.out.println(tray.poll());
        System.out.println(tray.peek());
        System.out.println(tray.pop());
    }
}

8. Loops that look or remove

A shrinking loop must really shrink.

loops that run until a deque is small or a limit is reached, and comparing what comes out

A ticket counter serves people until the line is empty. A packer takes boxes from a line until a weight limit is reached. Both are loops over a deque. One mistake makes a loop run for ever.

Reading the label on the front box does not move the box. If you keep reading it and never lift it, the next box never appears. peek reads; poll lifts. The picture stops at the empty shelf: poll then calmly hands back null.

Why does this matter for the loop? The condition asks about the size. Only a removing call changes the size, so only a removing call brings the condition closer to false.

Look and remove

peek and element return the head and keep it. poll, remove and pop return the head and delete it. On an empty deque, peek and poll give null; the other three throw.

Worked example: Drain the counter

Problem.

What does this print?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<Integer> tickets = new ArrayDeque<>(List.of(41, 42, 43));
        while (!tickets.isEmpty()) {
            int now = tickets.poll();
            System.out.println("serving " + now + ", left " + tickets.size());
        }
        System.out.println(tickets.poll());
    }
}

What is asked.

Four lines.

Idea.

Every turn removes one ticket, then reports what is left.

  1. Turn 1 removes 41, leaving 2.
  2. Turn 2 removes 42, leaving 1.
  3. Turn 3 removes 43, leaving 0, so the loop ends.
  4. The final poll finds nothing and returns null.

Answer.

serving 41, left 2, serving 42, left 1, serving 43, left 0, null

Common mistake.

Expecting an exception from the last poll.

A budget that stops the loop

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<Integer> shelf = new ArrayDeque<>(List.of(4, 6, 31, 2));
        int used = 0;
        while (!shelf.isEmpty() && used + shelf.peek() <= 15) {
            used += shelf.poll();
        }
        System.out.println(used + " " + shelf);
    }
}

The test peeks, the body polls

  1. The test peeks at the head: 0 + 4 is at most 15, so the body may take it.
  2. poll removed 4. The next test peeks at 6: 4 + 6 still fits.
  3. poll removed 6. Now 10 + 31 is over 15, so the loop stops and 31 stays.
What if

The budget loop prints 10 [31, 2].

  • The body becomes used += shelf.peek(); What prints?
    It prints 12 [4, 6, 31, 2].. Nothing is removed, but used grows by 4 each turn until one more would pass 15.
  • The body uses peek and the condition is only !shelf.isEmpty(). Does the loop end?
    No, it never ends.. The condition tests only the deque, and nothing in the body changes the deque.
  • The limit 15 becomes 100. What prints?
    It prints 43 [].. Every item fits, so the loop stops only when the deque is empty.

Now loops that take from both ends. With an odd count, one item is left in the middle. The condition decides whether the loop asks that single item for a partner.

Worked example: Dance partners

Problem.

Dancers pair up from the two ends of the floor. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<String> floor = new ArrayDeque<>(List.of("Ana", "Ben", "Cleo", "Dax", "Eli"));
        while (floor.size() > 1) {
            System.out.println(floor.pollFirst() + " + " + floor.pollLast());
        }
        System.out.println("solo " + floor.peek());
    }
}

What is asked.

The pairs and the last line.

Idea.

The loop runs while at least two remain.

  1. Size 5: Ana with Eli.
  2. Size 3: Ben with Dax.
  3. Size 1: the condition size() > 1 is false.
  4. peek shows who is left.

Answer.

Ana + Eli, Ben + Dax, solo Cleo

Common mistake.

Pairing Cleo with herself, or printing a pair with null.

Pairing from both ends, odd count

  1. Five dancers. The test size() > 1 holds, so a pair can be formed.
  2. Turn 1 removed the two ends.
  3. Turn 2 removed two more. One dancer is left, so the test is now false.
  4. The middle dancer is read with peek. A test of size() > 0 would have asked an empty end for a partner.

Strictly more than one

At least two

while (d.size() > 1) {
    d.pollFirst();
    d.pollLast();
}

At least one

while (d.size() > 0) {
    d.pollFirst();
    d.pollLast();
}

The difference. The number in the condition.

> 1 leaves a lone middle item; > 0 takes it and then receives null from the other end.

Worked example: Equal numbers, different objects

Problem.

Two readings of 5000 are polled into Integer variables. What prints?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Deque<Integer> readings = new ArrayDeque<>(List.of(5000, 5000));
        Integer first = readings.pollFirst();
        Integer last = readings.pollLast();
        System.out.println(first == last);
        System.out.println(first.equals(last));
        System.out.println(first == 5000);
    }
}

What is asked.

Three lines.

Idea.

== between two objects compares arrows. equals and a comparison with an int compare the number.

  1. Values this large are normally boxed into separate objects.
  2. first == last compares two references: on this JDK it is false.
  3. first.equals(last) compares the numbers: true.
  4. first == 5000 unboxes first and compares numbers: true.

Answer.

false, true, true

Common mistake.

Using == between two boxed values because it worked for small ones. Java only promises shared objects for -128 to 127.

When this breaks

A test such as a != b on two polled values compares objects when both sides are boxed. It works for Character values up to 127 and Integer values from -128 to 127, which Java shares. For anything else, use equals. If one side may be null and the other is an int, unboxing throws NullPointerException.

Practise this topic →

Weeks covering this topic

Other Java topics