Overview
Students traversed arrays in Topic 4.4 and learned the ArrayList methods in Topic 4.8 (size, add, get, set, remove, and the left shift after a removal). This topic puts the two together (4.9.A). Day 1 is the indexed traversal: a for or while loop with size() and get(i), forward, backward, and by steps (4.9.A.1), and the IndexOutOfBoundsException when an index leaves 0 through size() - 1 (4.9.A.3). Day 2 is the enhanced for loop on a list, what its loop variable can and cannot change, and the first trap: removing in a forward loop skips elements, so removal needs a special technique (4.9.A.2). Day 3 is the second trap: adding or removing inside an enhanced for loop can throw a ConcurrentModificationException, so it must not change the size (4.9.A.4).
One picture runs through all three days, and it is the deck’s title: mind the gap. When remove(i) closes the gap at index i, everything after it slides left. A forward loop that steps past that index misses the element that slid in; an enhanced loop loses its place altogether.
Stay inside the topic boundary. The standard list algorithms (sum, minimum and maximum, counting, searching, inserting while traversing) are Topic 4.10; today’s loop bodies print, replace with set, or remove. Do not use remove(Object), iterators, or contains; the CED’s ArrayList methods are the ones from Topic 4.8. Recursion is mentioned in 4.9.A.1 but taught in Topic 4.16, so say only “loops” today.
Teacher note
The slides are the Mind the Gap deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 uses slides 9–15, and Day 3 uses slides 16–21. The Mind the Gap puzzle worksheet (9 questions, about 30 minutes) is split across the three days: questions 1 and 2 in class on Day 1 and question 8 as Day 1 homework; question 3 in class on Day 2 and questions 4 and 7 as Day 2 homework; questions 6 and 5 in class on Day 3 and question 9 as Day 3 homework.
All demonstration files are in the topic’s examples/ folder.
- Day 1 demonstrations:
PlaylistIndexed,ListLength(compile error),ListLengthFixed,PlaylistBackward,PlaylistWhile,ScoresTooFar(exception),BackwardFromSize(exception),ShiftedStart(exception). - Day 2 demonstrations:
PlaylistEnhanced,TempsEnhanced,ShoutWrong,ShoutFixed,TeamBonus,DoubleLoopVar,RemoveSkip,RemoveHiddenBug,RemoveBackward,RemoveStayPut. - Day 3 demonstrations:
TaskListCrash(exception),TaskListFixed,CartAddCrash(exception),CartAddFixed,ScoresEnhancedRemove(exception),ScoresEnhancedFixed,SensorCleanup. - Printed only (exit ticket):
ExitRemoveEvens,ExitRemoveEvensFixed,ExitCartAdd.
Students who printed an ArrayList in Topic 4.8 know it shows as [a, b, c]; the worksheet and several demos rely on that.
Day 1 · Warm-up: From array to list
Show slide 2. Pairs get two minutes to say what must change when crew becomes an ArrayList<String>. Collect the two answers: crew.length becomes crew.size(), a method call with parentheses, and crew[i] becomes crew.get(i). Everything else, including the loop header’s shape, stays the same. Today’s first idea is that you already know how to do this.
Day 1 · Direct instruction: The indexed for loop, backward and by steps
- Goals (slide 3). Read the five goals. Tell students that goals 1 and 2 are today, goal 3 and the start of goal 4 are Day 2, and goals 4 and 5 are the two traps that finish on Day 3.
- Traversing (4.9.A.1, slides 4–5). Define a traversal: using a loop to visit all of a list’s elements, or an ordered run of them. Walk through
ListLoopon slide 5: start at 0, keep going whilei < crew.size(), read withcrew.get(i). Point to the table on the slide:.lengthbecomessize(),[i]becomesget(i), andcrew[i] = x;becomescrew.set(i, x);. RunPlaylistIndexedin the IDE to show the same loop on a playlist. - Array syntax on a list. Show
ListLengthbefore running it and ask whether it compiles. It does not:cannot find symbolforlengthandarray required, but ArrayList<String> foundfor the brackets.ListLengthFixedis the repair. - Backward and by steps (slide 6). Cover the output on the slide and ask for it first. The backward loop starts at
p.size() - 1, the last valid index, and runs whilei >= 0;i += 2visits 0, 2, 4. Read the callout aloud: backward starts atsize() - 1, notsize(). RunPlaylistBackwardand thenPlaylistWhile, which takes every other song with awhileloop. Point out where the three parts of theforheader went in thewhileversion (Topic 2.8).
Misconception: Array syntax on an ArrayList
Students type list.length or list[i] by habit, because arrays came first and the two look alike. An ArrayList is an object, so everything it does is a method call with parentheses. Give them the memory aid from the guide: arrays use .length and [ ]; ArrayLists use size() and get(i). The compile errors in ListLength are worth reading aloud once so students recognize them later.
Misconception: A backward loop stops at i > 0
Students write i > 0 because “greater than zero” feels like “still in the list.” Index 0 holds a real element, so the test must be i >= 0. Ask: “What is at index 0? Did the loop print it?” Worksheet question 8 is exactly this bug.
Day 1 · Direct instruction: One step too far
Slide 7 (4.9.A.3). Before revealing the right side, ask students to trace i <= laps.size() with three laps. i reaches 3, laps.get(3) asks for a box that does not exist (the dashed box on the slide), and Java throws an IndexOutOfBoundsException after printing the three laps. Stress three facts:
- Valid indices are 0 through
size() - 1.size()is a count, not a position. - The code compiles. The compiler cannot know how long the list will be, so the error happens at run time, and nothing after the crash runs.
- The same exception comes from
get,set, orremovewith any index outside the range, including a backward loop that starts atsize().
Run ScoresTooFar (three scores print, then the exception; Done never prints) and BackwardFromSize (nothing prints at all, because the very first call is get(3)).
Misconception: size() is the last index
Students write list.get(list.size()) for the last element, or i <= list.size() in a loop test, because the size “is how far the list goes.” A list of 3 has positions 0, 1, and 2, so size() is always one past the last index. Give them two checks for every header: what is the first index the body sees, and what is the last? Those should be 0 and size() - 1 (or the reverse going backward).
Day 1 · Guided practice: A while loop walks too
Students work slide 8 on whiteboards: bugs holds [ant, bee, fly, moth, wasp], i starts at 1 and goes up by 2. Expected answer: 1 bee and 3 moth; then i is 5, 5 < 5 is false, and the loop ends with no crash. Ask anyone who wrote a crash to show the value of i that would cause it.
Then pairs do worksheet question 1 (you’re the JVM). The answer is A (yo): the loop starts at index 2 and steps by -2, so it reads yew and then oak, and -2 fails i >= 0.
Teacher note
Question 1’s wrong choices: B (oy) walks forward; C (yeo) steps by -1; D (y) stops before index 0, as if the test were i > 0. Run ShiftedStart afterward if students need one more crash: it starts at 1 with <= and prints three colors before the exception.
Day 1 · Independent practice: Independent practice
Students work worksheet question 2 (pencil check) alone: for a list of 5, write the indexes each of six loops visits, or where it crashes. Check the two crash rows as you circulate: i <= pets.size() visits 0 through 4 and then crashes on 5, and for (int i = pets.size(); i > 0; i--) crashes right away on index 5. The i += 2 row from 1 visits 1 and 3; the while row with i += 3 visits 0 and 3. Unfinished rows and question 8 (one-token fix: change > to >= on line 5) are homework.
Day 1 · Closure: Closure
Students write on a sticky note the first and last index a backward loop over a list of 7 uses (6 and 0) and the loop header that does it (for (int i = list.size() - 1; i >= 0; i--)).
Day 2 · Warm-up: Headers on the whiteboard
Read out three jobs and have students write a loop header for each on whiteboards: every element of names front to back; every element back to front; every third element starting at index 0. Check the backward header for size() - 1 and >= 0. Then ask: “Which of these jobs needed the index for anything except get(i)?” Only the order did. That sets up the enhanced loop.
Day 2 · Direct instruction: The enhanced for loop and its copy
- Every element, no index (4.9.A.1, slides 9–10). Read the header aloud as “for each
Stringnameincrew.” The type matches the list’s element type, the variable gets each element in turn, front to back, and there is nosize()orget, so it cannot go out of bounds. The callout on slide 10 says when to use each loop; read it aloud. RunPlaylistEnhanced. Then showTempsEnhanced: with anArrayList<Integer>, the loop variable can be anint, because each element is unboxed (Topic 4.7). - The loop variable is a copy (slide 11). Cover the output and ask what the first
printlnshows. Most students say[hop!, skip!]. It is[hop, skip]:w = w + "!"builds a newStringand stores it only inw. The second loop uses the index andset, and that changes the list. This is the same rule students met for arrays in Topic 4.4. RunShoutWrongandShoutFixed. - But a mutator changes the object. Run
TeamBonus. Insidefor (Player p : team),p.addPoints(5)changes Ada’s and Ben’sPlayerobjects, becausepand the list refer to the same object (aliases, Topic 3.6). Point to the Watch Out box on page 2 of the worksheet (f.hop()on eachFrog f): it says the same thing. Summarize on the board: assigning topchanges nothing in the list; calling a method onpchanges the shared object; replacing an element needs an index andset.
Misconception: The loop variable writes back to the list
Students write word = word.toUpperCase(); or n = n * 2; inside an enhanced loop and expect the list to change, because the variable “is” the element. It is a copy. The code compiles and runs, so nothing warns them. Run DoubleLoopVar: the doubled values print inside the loop, and then the list prints unchanged as [4, 3, 5]. When elements must be replaced, use an indexed loop with set(i, …).
Misconception: An enhanced loop can never change anything
After the copy lesson, some students overcorrect and say the loop cannot affect the list at all. It cannot change which references the list holds, but it can change the objects those references lead to. TeamBonus is the counterexample; keep it on screen next to ShoutWrong while you take questions.
Day 2 · Guided practice: Long snacks only
Students work slide 12 on whiteboards: snacks holds [chips, nuts, pretzels, figs]; print each snack longer than 4 letters, then the size. Expected: chips, pretzels, 4. Ask why the size is still 4: the loop only reads.
Then pairs do worksheet question 3 (code tiles). The answer is the indexed header with <, then prices.set(i, prices.get(i) * 2);, the closing brace, and the println, printing [8, 20, 14]. Ask pairs to defend each decoy: for (int p : prices) with p = p * 2; runs but changes only the copy, so it prints [4, 10, 7]; the <= header reaches get(3) and throws an IndexOutOfBoundsException.
Day 2 · Direct instruction: A forward loop skips
Slides 13–14 (4.9.A.2). Ask students to predict the output of the “remove the negatives” loop on slide 14 before revealing the table. Most predict [5, 4]. Walk the table row by row with the list drawn as boxes on the board. At i = 1, -2 is removed and -7 slides left into index 1; then i++ moves to index 2, which is now 4. The -7 is never checked, and the output is [5, -7, 4]. It compiles and does not crash; it is just wrong. This is what skipping means.
Then run RemoveSkip (58 survives) and RemoveHiddenBug, the same loop on [62, 85, 58, 90], which happens to print the right answer, [85, 90]. Ask: “Why did this list hide the bug?” Each low score is followed by a score that should stay, so skipping it does no harm. The bug shows only when two elements to remove sit next to each other.
Misconception: It worked on my test, so it works
Students test the removal loop once, see the right output, and move on. Because the skip only matters when two elements to remove are adjacent, one test can hide it. Teach the question “What if two in a row need to be removed?” and make students add such a case to every removal test this unit. RemoveHiddenBug next to RemoveSkip makes the point.
Misconception: Calling size() every pass prevents skipping
Students think i < list.size() keeps the loop correct because it sees the shrinking list. It keeps the loop in range, which prevents a crash, but it does nothing about the element that slid into index i. Worksheet question 7 is built on this claim.
Day 2 · Direct instruction: Two ways not to skip
Slide 15. Read the callout: removing during a traversal needs a special technique so nothing is skipped (the CED’s own words).
- Fix 1: walk backward. A removal shifts only the elements after index
i, and going backward the loop has already checked all of them. The elements still to check, at lower indices, do not move. RunRemoveBackwardand trace it on the board. - Fix 2: move on only if kept. A
whileloop that doesi++only in theelsebranch. After a removal,istays put and the next pass checks the element that slid in. RunRemoveStayPut.
Both print [5, 4] on the slide. Ask which one students would pick; either is correct, and backward is usually one header change.
Day 2 · Closure: Closure
Point students to the Think First box on page 2 of the worksheet: “Your loop is at i = 2 and removes the element there. Which element is at index 2 now? Will the loop ever check it after i++?” Students write their answer in the margin (the element that was at index 3; no, a forward loop skips it). Homework: worksheet question 4 (snippet pool: words.size() - 1, i >= 0, i--, printing [frog, pond]), which settles the Think First box, and question 7 (two truths and a lie).
Day 3 · Warm-up: X marks the skip
Show slide 16. Students write the output alone: marks holds [ok, x, x, ok, x], and the forward loop prints [ok, x, ok]. The second x slid into index 1 after the first was removed and was never checked. Then they change the header so every x is removed: for (int i = marks.size() - 1; i >= 0; i--). Accept the while fix too, but note it changes more than the header. Use the minute left to check homework question 7: claim 3 is the lie; temps ends as [40, 28, 55].
Day 3 · Direct instruction: Changing the size in an enhanced for loop
- The crash (4.9.A.4, slides 17–18). The enhanced loop keeps its own place in the list behind the scenes and assumes the size does not change. Show the left side of slide 18 and ask for the output. After
Done: dishes, the first pass removes element 0; when the loop fetches the next element, Java throws a ConcurrentModificationException.All donenever prints. The right side does the same job with awhileloop that checkssize()and removes index 0, and it works. - Live. Run
TaskListCrashandTaskListFixed, thenCartAddCrash: adding is just as bad as removing.CartAddFixeduses an indexed loop, which simply sees the longer list on its next test. - A counter does not help. Show
ScoresEnhancedRemove: the student keeps their own index and callsremove(index)inside the enhanced loop. The index is right, but the size still changes during an enhanced loop, so it still throws.ScoresEnhancedFixedis a backward indexed loop. - The rule. Java does not promise to catch every size change; occasionally such a loop ends early with no exception. Either way the program cannot be trusted, so the rule is absolute: never add or remove inside an enhanced
forloop.
Misconception: The compiler will stop me
Students expect a loop that breaks a rule to be a compile error. Changing the size inside an enhanced loop compiles; the exception happens at run time, when the loop fetches the next element. Ask students to sort each of today’s bugs into “won’t compile” (array syntax on a list), “crashes” (bad index, size change in an enhanced loop), and “runs but wrong” (skipping, assigning to the loop variable). Worksheet question 6 practices exactly this sort.
Misconception: Assigning to the loop variable causes a ConcurrentModificationException
Once students learn the exception, they blame it for everything that happens inside an enhanced loop. Only adding or removing elements changes the size. n = 0; inside the loop is harmless and useless: the list is unchanged and nothing crashes (worksheet question 6, snippet 2).
Day 3 · Direct instruction: Which loop for the job?
Slide 19. Go row by row and ask the class for one example job for each. The last row is the one that matters most today: if the size will change, never use an enhanced for. If time allows, show SensorCleanup, which uses three traversals in one program (indexed to print positions, backward to remove failed readings, enhanced to print the clean list) and say why each was chosen.
Day 3 · Guided practice: You’re the compiler
Students do worksheet question 6 in pairs, then share. For each snippet, nums starts as [3, 6, 9]:
- Compiles; prints 3, 6, 9, then an IndexOutOfBoundsException (
<=letsireach 3). - Compiles; prints
[3, 6, 9](nis a copy). - Compiles; throws a ConcurrentModificationException (the list grows during an enhanced loop).
- Does not compile: a list has
size(), notlength.
Teacher note
Snippet 3 prints nothing before the exception, since the body only adds. If students ask why it does not run forever (the list keeps growing), the answer is that Java stops it with the exception on the second fetch.
Day 3 · Independent practice: Independent practice
Students complete worksheet question 5 (face-off) alone. Answers: end, replace, nothing, ConcurrentModificationException, left, skips, backward. Question 9 (who am I?) is homework.
Day 3 · Closure: Closure and exit ticket
Spend one minute on slide 20: point to a vocabulary card and ask for a loop header or a line of code that shows it. Then slide 21: partners finish the sentence starter, “When I remove at index i, only the elements after i move, and going backward I have already checked them.” Give the exit ticket for the last five minutes. Question 1 checks traversal headers and the IndexOutOfBoundsException (4.9.A.1, 4.9.A.3), question 2 checks skipping and its fix (4.9.A.2), and question 3 checks the ConcurrentModificationException (4.9.A.4). Re-teach the weakest one at the start of Topic 4.10, where removing and inserting during a traversal come back.