Skip to content

Course navigation

For teachersTopic 4.9 · Lesson kit

ArrayList Traversals

  • 3 class periods
  • 45 minutes each
  • Objective 4.9.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
3 class periods of 45 minutes
Learning objectives
4.9.A
Essential knowledge
4.9.A.14.9.A.24.9.A.34.9.A.4
Materials
Projector and the Mind the Gap slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)IDE on every computer (Days 1 and 3)Printed Mind the Gap puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upfrom array to list (slide 2)
  2. 0:05–0:2015 minDirect instructionthe indexed for loop, backward and by steps (slides 3–6)
  3. 0:20–0:288 minDirect instructionone step too far (slide 7)
  4. 0:28–0:3810 minGuided practicea while loop walks too (slide 8) and worksheet question 1
  5. 0:38–0:435 minIndependent practiceworksheet question 2
  6. 0:43–0:452 minClosurefirst index, last index

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upheaders on the whiteboard
  2. 0:05–0:1712 minDirect instructionthe enhanced for loop and its copy (slides 9–11)
  3. 0:17–0:2710 minGuided practicelong snacks only (slide 12) and worksheet question 3
  4. 0:27–0:4013 minDirect instructiona forward loop skips, and two fixes (slides 13–15)
  5. 0:40–0:455 minClosurethe worksheet's Think First box

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:077 minWarm-upX marks the skip (slide 16)
  2. 0:07–0:1710 minDirect instructionchanging the size in an enhanced for loop (slides 17–18)
  3. 0:17–0:225 minDirect instructionwhich loop for the job? (slide 19)
  4. 0:22–0:3210 minGuided practiceworksheet question 6
  5. 0:32–0:375 minIndependent practiceworksheet question 5
  6. 0:37–0:403 minClosurevocabulary and mind the gap (slides 20–21)
  7. 0:40–0:455 minExit ticket

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

  1. 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.
  2. 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 ListLoop on slide 5: start at 0, keep going while i < crew.size(), read with crew.get(i). Point to the table on the slide: .length becomes size(), [i] becomes get(i), and crew[i] = x; becomes crew.set(i, x);. Run PlaylistIndexed in the IDE to show the same loop on a playlist.
  3. Array syntax on a list. Show ListLength before running it and ask whether it compiles. It does not: cannot find symbol for length and array required, but ArrayList<String> found for the brackets. ListLengthFixed is the repair.
  4. 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 while i >= 0; i += 2 visits 0, 2, 4. Read the callout aloud: backward starts at size() - 1, not size(). Run PlaylistBackward and then PlaylistWhile, which takes every other song with a while loop. Point out where the three parts of the for header went in the while version (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:

  1. Valid indices are 0 through size() - 1. size() is a count, not a position.
  2. 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.
  3. The same exception comes from get, set, or remove with any index outside the range, including a backward loop that starts at size().

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

  1. Every element, no index (4.9.A.1, slides 9–10). Read the header aloud as “for each String name in crew.” The type matches the list’s element type, the variable gets each element in turn, front to back, and there is no size() or get, so it cannot go out of bounds. The callout on slide 10 says when to use each loop; read it aloud. Run PlaylistEnhanced. Then show TempsEnhanced: with an ArrayList<Integer>, the loop variable can be an int, because each element is unboxed (Topic 4.7).
  2. The loop variable is a copy (slide 11). Cover the output and ask what the first println shows. Most students say [hop!, skip!]. It is [hop, skip]: w = w + "!" builds a new String and stores it only in w. The second loop uses the index and set, and that changes the list. This is the same rule students met for arrays in Topic 4.4. Run ShoutWrong and ShoutFixed.
  3. But a mutator changes the object. Run TeamBonus. Inside for (Player p : team), p.addPoints(5) changes Ada’s and Ben’s Player objects, because p and 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 each Frog f): it says the same thing. Summarize on the board: assigning to p changes nothing in the list; calling a method on p changes the shared object; replacing an element needs an index and set.

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).

  1. 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. Run RemoveBackward and trace it on the board.
  2. Fix 2: move on only if kept. A while loop that does i++ only in the else branch. After a removal, i stays put and the next pass checks the element that slid in. Run RemoveStayPut.

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

  1. 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 done never prints. The right side does the same job with a while loop that checks size() and removes index 0, and it works.
  2. Live. Run TaskListCrash and TaskListFixed, then CartAddCrash: adding is just as bad as removing. CartAddFixed uses an indexed loop, which simply sees the longer list on its next test.
  3. A counter does not help. Show ScoresEnhancedRemove: the student keeps their own index and calls remove(index) inside the enhanced loop. The index is right, but the size still changes during an enhanced loop, so it still throws. ScoresEnhancedFixed is a backward indexed loop.
  4. 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 for loop.

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]:

  1. Compiles; prints 3, 6, 9, then an IndexOutOfBoundsException (<= lets i reach 3).
  2. Compiles; prints [3, 6, 9] (n is a copy).
  3. Compiles; throws a ConcurrentModificationException (the list grows during an enhanced loop).
  4. Does not compile: a list has size(), not length.

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.

Exit ticket

Question 1 · Multiple choice

nums is an ArrayList<Integer> holding [5, 10, 15, 20]. Each loop has the body System.out.print(nums.get(i) + " ");. Which loop prints 20 10 and then ends normally?

  1. for (int i = nums.size() - 1; i > 0; i--)
  2. for (int i = nums.size(); i > 0; i -= 2)
  3. for (int i = nums.size() - 1; i >= 0; i -= 2)
  4. for (int i = 0; i < nums.size(); i += 2)
Check your reasoning

C. It starts at the last index, 3, and steps by -2: index 3 (20), then index 1 (10). Then i is -1, -1 >= 0 is false, and the loop ends.

  • A is wrong: it steps by -1, so it prints 20 15 10. It also stops before index 0 because the test is i > 0.
  • B is wrong: it starts at nums.size(), which is 4. The first call, nums.get(4), throws an IndexOutOfBoundsException before anything prints. The last index is size() - 1.
  • D is wrong: it walks forward from index 0 and prints 5 15.

Question 2 · Multiple choice

This program is supposed to remove every even number. Which statement is correct?

ExitRemoveEvens.java
import java.util.ArrayList;

public class ExitRemoveEvens
{
    public static void main(String[] args)
    {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        nums.add(3);
        nums.add(8);
        nums.add(10);
        nums.add(5);
        nums.add(12);

        for (int i = 0; i < nums.size(); i++)
        {
            if (nums.get(i) % 2 == 0)
            {
                nums.remove(i);
            }
        }
        System.out.println(nums);
    }
}
  1. It prints [3, 5]: the program already works.
  2. It prints [3, 10, 5]; the header for (int i = nums.size() - 1; i >= 0; i--) fixes it.
  3. It throws an IndexOutOfBoundsException, because the test keeps using the size the list had when the loop started.
  4. It prints [3, 10, 5]; the header for (int i = nums.size(); i >= 0; i--) fixes it.
Check your reasoning

B.

i List before this pass nums.get(i) Action
0 [3, 8, 10, 5, 12] 3 keep
1 [3, 8, 10, 5, 12] 8 remove; 10 slides to index 1
2 [3, 10, 5, 12] 5 keep (10 was never checked)
3 [3, 10, 5, 12] 12 remove
4 [3, 10, 5] 4 < 3 is false; loop ends

10 survives: removing 8 slid it into index 1, and i++ moved the loop on to index 2. Traversing backward fixes it, because a removal only shifts elements the loop has already checked:

ExitRemoveEvensFixed.java
import java.util.ArrayList;

public class ExitRemoveEvensFixed
{
    public static void main(String[] args)
    {
        ArrayList<Integer> nums = new ArrayList<Integer>();
        nums.add(3);
        nums.add(8);
        nums.add(10);
        nums.add(5);
        nums.add(12);

        for (int i = nums.size() - 1; i >= 0; i--)
        {
            if (nums.get(i) % 2 == 0)
            {
                nums.remove(i);
            }
        }
        System.out.println(nums);
    }
}

This prints [3, 5].

A misses the shift: after a removal, the next element slides into the index just checked and is skipped. C thinks the test is worked out once, but nums.size() is called on every pass and sees the shorter list, so no index goes past the end. D goes backward but starts at nums.size(), which is 5; nums.get(5) throws an IndexOutOfBoundsException, because the last index is size() - 1.

Question 3 · Multiple choice

What happens when this program runs?

ExitCartAdd.java
import java.util.ArrayList;

public class ExitCartAdd
{
    public static void main(String[] args)
    {
        ArrayList<String> cart = new ArrayList<String>();
        cart.add("tea");
        cart.add("rice");
        cart.add("jam");

        for (String item : cart)
        {
            System.out.println(item);
            if (item.equals("tea"))
            {
                cart.add("honey");
            }
        }
        System.out.println("Checkout");
    }
}
  1. It prints tea, rice, jam, honey, and Checkout, because the loop reaches the element it added.
  2. It prints tea, rice, jam, and Checkout: honey is added, but the loop visits only the three elements that were there when it started.
  3. It does not compile, because an enhanced for loop cannot add to the list it traverses.
  4. It prints tea, then stops with a ConcurrentModificationException; an indexed for loop should be used instead.
Check your reasoning

D. On the first pass, item is "tea", so the body adds "honey" and the list changes size during an enhanced for loop. When the loop goes to fetch the next element, Java detects the change and throws a ConcurrentModificationException; Checkout never prints. An indexed for loop (for (int i = 0; i < cart.size(); i++) with cart.get(i)) sees the new size and prints tea, rice, jam, honey, and Checkout.

A is what the indexed loop prints, not the enhanced for loop. B thinks the loop works on a snapshot of the list, but it traverses the list itself, and the change stops it. C expects the compiler to catch it; the code compiles, and the problem appears only at run time.