The largest share of a paper.
Open the interactive lessons →Collections Framework past questions
Contents
- Which container?
- Three map orders
- Totals: getOrDefault and merge
- Sets, sameness and order
- Removing while walking
- List iterators: edit while walking
- Stacks, queues and deques
- 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 to | Interface | Usual classes |
|---|---|---|
| keep positions, allow repeats | List | ArrayList, LinkedList |
| hold each value once | Set | HashSet, LinkedHashSet, TreeSet |
| look a value up by a key | Map | HashMap, LinkedHashMap, TreeMap |
| add and remove at the ends | Deque | ArrayDeque, 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.
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.
- The list receives 12, 7 and 30.
- Each turn unboxes one element into
mmand adds it tototal, giving 12, 19, 49. total / rain.size()is49 / 3with twointvalues, 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.
The rain program prints total 49 and average 16.
- The loop header becomes
for (Long mm : rain), andtotalstill receivesmm. Does it compile?
It does not compile.. AnIntegerelement is not aLong.IntegerandLongnever convert into each other. - The loop header becomes
for (Integer mm : rain). What prints?
The output is unchanged:total 49,average 16..total += mmunboxes theIntegerfor the addition. - The last line divides
(double) total / rain.size(). Is the average still 16?
No: the second line prints a fraction that startsaverage 16.33.. Onedoubleoperand 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
- The map stores two arrows, one per key. Each list is its own object on the heap.
get("east")hands back the arrow, soviewreaches the very same list. Nothing was copied.view.add(24)changes that one list. The map sees the new value when printed.- Assigning
viewagain 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.
values()gives one list per club.- The first name longer than the empty text is kept, and only a longer one replaces it.
- The lengths include
Bartholomewwith 11 letters; no other name is as long. 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].
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
| Class | Iteration order | null key |
|---|---|---|
HashMap | unspecified: no promise at all | one allowed |
LinkedHashMap | order of first insertion | one allowed |
TreeMap | keys sorted in natural order | rejected |
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.
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
- The first put: both maps hold one pair.
C2joins the end of the linked map, but moves to the front of the tree map because C comes before M.K9goes last in arrival order, and between C and M in sorted order.C2again: 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.
- Key 30 gets
Zed, then key 4 getsAma. - The third
putreplacesZedwithLinand returnsZed. - Numbers sort by size, so 4 comes before 30 in both
keySet()andvalues(). - 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.
indexstarts with the three entries ofseen, sorted by key: heron, owl, wren.remove("owl")changesindexonly.put("kite", 4)adds a key that sorts between heron and wren.indexno longer hasowl, butseenstill 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.
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}, thentrue true..owlis 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}, thenfalse true..wrenalready 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.
"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.
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.
b: missing, so 0 + 1 = 1.o: missing, so 1.bagain: old 1, new 2. Thenbonce more: 3.iandnare new, each 1.- 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.
- No value for the key (or a stored
null): store the given value. The function does not run. 2. A value exists: callfunction(oldValue, givenValue)and store its result. 3. If that result isnull: remove the key. The given value itself must not benull.
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
vanis missing, somergestores 40 as it is. The lambda is not run.bikeis also new. Again the value is stored directly.vanexists. The lambda receives the stored value first and the new value second.- 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.
gluehas 8, so the function runs:8 - 5stores 3.tapehas 3 and 3 are sold.have.equals(sold)is true, so the function answersnullandtapeis removed.pinshas no value, so 7 is stored directly. The function does not run, although it is a subtraction.- 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.
The shelf program prints {glue=3, pins=7}.
- The first function becomes
(have, sold) -> sold - have. What happens toglue?
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
gluecall becomesshelf.put("glue", 5);What prints?
It prints{glue=5, pins=7}..putignores the old value completely. - The
pinscall is made twice. What is the value ofpins?
It prints{glue=3, pins=0}.. The second call finds 7, runs7 - 7and stores 0. A result of 0 is a value, notnull.
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.
gateis new: storesopen.pumpis new: storeson.gateexists: the function buildsopen>shut.- The tree map prints
gatebeforepump.
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.
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
| Class | Order when walked | How a repeat is detected |
|---|---|---|
HashSet | unspecified | hashCode, then equals |
LinkedHashSet | order of first insertion | hashCode, then equals |
TreeSet | sorted in natural order | comparing for order: 0 means the same |
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.
R12,B40andA07are each accepted the first time.- The repeats are
R12,B40andR12; the tree set holds each once, sorted: B40, R12. seen.remove("R12")istrue;seen.remove("Z99")isfalse.- Adding
R12again 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
- This model has four buckets and uses
hashCode % 4. Code 6 leads to bucket 2, which is empty, so it is stored. - Code 9 leads to bucket 1. Also empty, so a second element is stored.
- A new
Stamp(6): only bucket 2 is searched.equalssays it matches, soaddreturnsfalse. contains(new Stamp(9))goes straight to bucket 1 and finds an equal element.
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
equalscalls the two stamps equal, but the inheritedhashCodeknows nothing aboutcode.- The two codes are almost always different. Then the set does not match the first stamp and stores a second one.
- Add
hashCodereturningcode: equal stamps share a bucket,equalsis asked, and the second is refused.
The stamp program prints true, true, false, 2 true.
hashCodereturns1for every stamp. What prints?
The same four lines print:true,true,false,2 true.. The contract still holds. All stamps share a bucket, soequalsdoes all the work.- The
hashCodemethod is deleted. What is the third line?
On this run it printstrue, 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. albumis built asnew TreeSet<>()and nothing else changes. What happens at the firstadd?
It compiles and then throwsClassCastException.. A tree set must compare elements for order, andStampoffers no such comparison.
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.
sawhas 3 letters, so key 3 gets a new set holdingsaw.nails,brushandhingeall have 5 letters and share one set.- The second
sawfinds its set and is refused as a repeat. - 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.
- The set starts as 2, 7, 11.
add(11)finds 11 already present:false.remove(7)deletes it:true.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.
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().
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
- A fresh iterator points before the first element. Nothing has been returned yet.
next()returns 4 and steps forward. 4 is not over 60, so it stays.next()returns 65, which must go.remove()deletes the last returned element and moves the cursor back by one, so 90 is not skipped.next()returns 90.- 90 is removed in the same safe way.
- 12 is visited and kept.
hasNext()is nowfalse, 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.
it.next()returnsnorth, which prints.it.remove()tries to shrink the list.- A list from
List.ofcannot change, so the call throws. - The last line is never reached.
Answer.
north, then UnsupportedOperationException
Common mistake.
Calling this a compilation error. The call compiles, because Iterator declares remove.
The waiting-list program prints [4, 12].
walker.remove();is written twice in theifbody. What happens?
It throwsIllegalStateExceptionat the first time over 60.. The second call has no unremoved element: the one fromnext()is already gone.- The line
int minutes = walker.next();is replaced byint minutes = 99;What happens?
It throwsIllegalStateExceptionon the first turn..remove()was called before anynext(), 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.
memo: notx-, and 4 letters, so it is counted.x-old: removed.invoice: counted.x-spam: removed.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
- A for-each loop builds an iterator that notes how many structural changes the list has had.
- The loop body gets
Adaand prints it. crew.remove(name)goes around the iterator. The list counts a change; the iterator does not know.hasNext()says yes (1 is not the size 3).next()compares the counts and throwsConcurrentModificationException.
"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
| Call | Effect |
|---|---|
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 |
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.
- Two
next()calls return 10 and 20. The cursor is after 20. previous()crosses 20 backwards and returns it.next()crosses it again: 20.- 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
- Gap 0 is before the first element.
next()jumps over 10 and returns it.next()returns 20. The cursor is in gap 2.previous()jumps back over 20 and returns the same element again.- One more
next()returns 20 a third time. - 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);
}
}
The track program prints [0-intro, 1-rain, 2-outro].
cur.set(...)becomescur.remove();What prints?
It prints[].. Each element is deleted right after it is returned.curis declared asIterator<String>and built withtracks.iterator(), keeping the loop body. Does it compile?
It does not compile..Iteratorhas neithernextIndexnorset.- The line
int at = cur.nextIndex();moves belowString t = cur.next();What prints?
It prints[1-intro, 2-rain, 3-outro].. Afternext()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.
- After the first
gym,restis inserted and the cursor is after it. - The walk continues with
art, then the secondgym, followed by another insert. - First print:
[maths, gym, rest, art, gym, rest]. - Walking back, each
restis returned byprevious()and removed. - The cursor ends at the start:
nextIndex()is 0 andnext()givesmaths.
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.
"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)
| Job | Head | Tail |
|---|---|---|
| add | addFirst, offerFirst, push | addLast, offerLast, add, offer |
| remove | pollFirst, poll, pop, remove, removeFirst | pollLast, removeLast |
| look | peekFirst, peek, element, getFirst | peekLast, 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.
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
- The first job goes into both containers.
- Both print in the order added, yet their exits differ: a stack leaves from the newest end.
pop()took the newest,poster.poll()took the oldest,cv.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.
Stackprints from the bottom: the first pushed comes first.- A deque prints from its head, and
pushputs each new item at the head. - So the two lists look reversed.
- 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.
The copy shop prints poster cv on its second line.
- The deque uses
print.push(job)in place ofprint.add(job). What is the second line?
It printsposter poster..pushputs each job at the head, sopollreturns the newest: the deque now behaves as a stack. print.poll()becomesprint.pollLast(). What is the second line?
It printsposter poster.. The tail holds the job added last.- The line
print.add(job);becomesprint.addFirst(job);andprint.poll()becomesprint.pollLast(). What is the second line?
It printsposter 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.
addandaddLast:Mia Raj.pushandaddFirstuse the head:Kai Eve Mia Raj.offeruses the tail:Solgoes last.pollFirstgivesKai,pollLastgivesSol.popgivesEve;peekLastreadsRajwithout 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?
addandaddLastboth join at the tail.pushjoins at the head, in front of everyone.addFirstalso uses the head.offeris the queue's way to join the tail.pollFirstremovedKaifrom the head andpollLastremovedSolfrom the tail.popremovedEvefrom the head.peekLastonly readRaj.
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.
"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.
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.
- Turn 1 removes 41, leaving 2.
- Turn 2 removes 42, leaving 1.
- Turn 3 removes 43, leaving 0, so the loop ends.
- The final
pollfinds nothing and returnsnull.
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
- The test peeks at the head: 0 + 4 is at most 15, so the body may take it.
pollremoved 4. The next test peeks at 6: 4 + 6 still fits.pollremoved 6. Now 10 + 31 is over 15, so the loop stops and 31 stays.
The budget loop prints 10 [31, 2].
- The body becomes
used += shelf.peek();What prints?
It prints12 [4, 6, 31, 2].. Nothing is removed, butusedgrows by 4 each turn until one more would pass 15. - The body uses
peekand 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 prints43 [].. 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.
- Size 5:
AnawithEli. - Size 3:
BenwithDax. - Size 1: the condition
size() > 1is false. peekshows 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
- Five dancers. The test
size() > 1holds, so a pair can be formed. - Turn 1 removed the two ends.
- Turn 2 removed two more. One dancer is left, so the test is now
false. - The middle dancer is read with
peek. A test ofsize() > 0would 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.
- Values this large are normally boxed into separate objects.
first == lastcompares two references: on this JDK it isfalse.first.equals(last)compares the numbers:true.first == 5000unboxesfirstand 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.
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.