Overview
This topic has one learning objective (4.10.A) and two essential knowledge statements. 4.10.A.1 lists eleven standard ArrayList algorithms; 4.10.A.2 says some algorithms traverse several strings, arrays, or lists at once. The day split follows the deck’s four parts:
- Day 1: the Topic 4.5 array algorithms carried over to a list: sum, average, minimum, maximum, “at least one”, “all”, and “how many”.
- Day 2: consecutive pairs and duplicates, then the first algorithm that changes the list while traversing it: inserting.
- Day 3: deleting while traversing, then shifting and rotating with
removeandadd. - Day 4: reversing, building a filtered list, and traversing two collections side by side (4.10.A.2), then the exit ticket.
Students already know the array versions of the Day 1 algorithms (Topic 4.5), the ArrayList methods size, get, set, add, and remove (Topic 4.8), indexed and enhanced for loop traversals with their exceptions (Topic 4.9), wrapper classes and unboxing (Topic 4.7), and nested loops (Topic 2.11). The new skill is not a new method; it is keeping track of indexes while the list changes underneath the loop. Stay inside the topic boundary: no 2D arrays (Topic 4.11), no searching or sorting algorithms by name (Topics 4.14 to 4.15), and no recursion.
One idea runs through Days 2 and 3: ask which way the elements moved. add(i, value) pushes later elements right, so the loop must step past the new element. remove(i) slides later elements left, so the loop must not step past the element that arrived. The worksheet’s face-off (question 3) and the deck’s closure (slide 22) both turn on this.
Teacher note
The slides are the List Surgery deck (22 slides); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 uses slides 9–13, Day 3 uses slides 14–18, and Day 4 uses slides 19–22. The List Surgery puzzle worksheet (9 questions, about 30 minutes) is spread across the four days: question 1 on Days 1 and 2, question 8 on Day 2, questions 2, 3, and 5 on Day 3, and questions 4, 6, and 7 on Day 4. Question 9 (who am I?) and any of question 6 not finished in class are homework after Day 4.
Every demonstration file is a full program in the topic’s examples/ folder. Open the day’s files in the IDE before class so each demo is one click.
- Day 1:
SumAverage.java,MinMaxTemps.java,MaxStartZero.java,MaxStartFirst.java,LongestWord.java,GradeChecks.java,TagChecks.java,CountRange.java,FlagElseBug.java,FlagElseFixed.java. - Day 2:
ConsecutiveRises.java,PairsTooFar.java(run-time error),AdjacentRepeats.java,HasDuplicate.java,DupSelfBug.java,DupSelfFixed.java,IntegerEqualsBug.java,IntegerEqualsFixed.java,InsertStudy.java,InsertAfterEven.java,InsertInOrder.java. - Day 3:
RemoveSkipBug.java,RemoveForwardFixed.java,RemoveBackward.java,RemoveEnhancedFor.java(run-time error),RemoveShortWords.java,ShiftWindow.java,RotateTurns.java. - Day 4:
ReverseList.java,ReverseTwice.java,SwapNoTemp.java,BeforeM.java,FilterAddBug.java(run-time error),FilterAddFixed.java,HonorRoll.java,QuizKey.java,ShortAnswersBug.java(run-time error),ShortAnswersFixed.java,CleanReadings.java. - Printed only (exit ticket):
ExitDropLow.javaandExitSortedCheck.java.
Day 1 · Warm-up: Same algorithm, new container
Show slide 2: the Topic 4.5 maximum of an int[] named scores. Students rewrite it for an ArrayList<Integer> named scores, circling what changes and underlining what stays. What changes: the declaration (an ArrayList built with add calls), scores[0] and scores[i] (both become scores.get(...)), and scores.length (becomes scores.size(), with parentheses because it is a method call). What stays: int best, the loop header’s shape, the > comparison, and the assignment to best. Leave “same algorithm, new way to reach the elements” on the board.
Day 1 · Direct instruction: Sum, average, minimum, maximum
- Goals (slide 3). Read the five goals; Day 1 covers goal 1.
- The translation table (4.10.A.1, slides 4–5). Point to the table on slide 5:
arr.lengthislist.size(),arr[i]islist.get(i), andarr[i] = v;islist.set(i, v);. Walk throughScores.javaon the slide: one loop keeps a running total and a best-so-far, and printsAverage: 86.0andBest: 95. Ask: “What doesscores.get(i)return, and how can we add it to anint?” It returns anInteger, which Java unboxes to anint(Topic 4.7). - Run
SumAverage.java(total 27000 steps, average 5400.0). Point to the cast ontotal, not on the division, and to the slide’s reminder: an average divides bysize(), so the list must not be empty. That is a precondition. - Minimum and maximum together. Run
MinMaxTemps.java(Lowest: -8,Highest: 5): both start attemps.get(0), and the loop compares each element with both. - Start at a real element (slide 6). Show
Freezer.javaand ask for the output before revealing it: the three temperatures are all below 0, so the maximum stays at its starting 0, a value that is not in the list. Then runMaxStartZero.java(Highest: 0) andMaxStartFirst.java(Highest: -2). - Not only numbers.
LongestWord.javakeeps the longestStringso far by comparinglength()values and printsbanana. The best-so-far pattern works for any property you can compare.
Misconception: Starting a maximum at 0
Students start a maximum at 0 because sums and counters start at 0. If every element is negative, the answer is 0, which is not even in the list (slide 6, MaxStartZero.java). Start a minimum or maximum at list.get(0) and loop from index 1. Ask “Could every value be below my starting value?” before accepting any start.
Day 1 · Direct instruction: Any, all, and how many
- Three questions, three starts (4.10.A.1, slide 7). Read the table on the slide: “any?” starts
falseand changes when one element has the property; “all?” startstrueand changes when one element lacks it; “how many?” starts at 0 and adds 1 per match. TraceRides.javawith the class: 47 makesanyShorttrue, no height is below 42 soallTallstays true, and 52 and 60 are the two heights at least 50. - Run
GradeChecks.java(Any below 70: true,All passing: true,A grades: 2) and ask students to predict each line first. - One loop, two jobs.
TagChecks.javauses oneif/else: a hashtag adds to the count, and anything else setsallTagsto false.CountRange.javacounts values from 10 to 20 with&&(Topic 2.5) and sets an “over 50” flag in the same loop (3 true). - The rule on the slide: a flag switches once and never switches back.
Day 1 · Guided practice: Is every battery charged?
Show slide 8. Pairs trace allCharged after each of the three elements: 80 leaves it true, 15 sets it false, and 90 sets it back to true, so the program prints true. It is wrong: one battery is at 15. Ask what the fix is: delete the else block, so nothing can switch the flag back. Run FlagElseBug.java (All passing: true) and FlagElseFixed.java (All passing: false) to show the same bug with grades.
Misconception: An else that switches the flag back
Students add an else because it feels like “the other case.” With it, the flag reports only the last element. An “all” flag only ever moves from true to false; an “any” flag only from false to true. Have students trace the flag after every element, as slide 8’s hint says, rather than only after the one that should flip it.
Day 1 · Independent practice: Independent practice
Hand out the puzzle worksheet. Students do question 1 (pencil check), the first seven rows only: sum 25, average 5.0, maximum 9, minimum -3, three elements greater than 5, true for “at least one negative”, and false for “all even”. Circulate and check that the average is written as 5.0, not 5, and that students start the maximum and minimum at temps.get(0).
Teacher note
The last row of question 1 (consecutive pairs) is Day 2’s warm-up. The rest of the worksheet waits for the later days; ask students to keep it in their folders.
Day 1 · Closure: Closure
Ask: “Where does each one start: a sum, a maximum, an ‘any’ flag, an ‘all’ flag, a count?” Students answer on scrap paper: 0, the first element, false, true, 0. Ask one more: “Which one can never change back?” Both flags.
Day 2 · Warm-up: Question 1, last row
Students finish question 1: how many consecutive pairs of temps (6, -3, 9, 4, 9) have a larger second element? Ask first how many pairs a 5-element list has. Four: (6, -3), (-3, 9), (9, 4), (4, 9). Two of them rise. Keep “5 elements, 4 pairs” on the board for the next part.
Day 2 · Direct instruction: Consecutive pairs
- Goal 2 (slides 3 and 9). Today is two elements at a time.
- Pairs stop one early (4.10.A.1, slide 10). Show the diagram of five hike heights and four pairs. The loop runs
i < hike.size() - 1so thatget(i + 1)stays in range; the program printsDrops: 2(135 to 130 and 150 to 145). The other correct form starts ati = 1and comparesget(i - 1)withget(i). - Run
ConsecutiveRises.java(Rises: 3,Biggest jump: 5): the pair loop also keeps a maximum of the differences. - Go one step too far. Show
PairsTooFar.javaand ask what happens withi < prices.size(). Run it: four pairs print, then anIndexOutOfBoundsExceptionati = 4, whenget(5)is asked for. Mention that the exact message wording can vary between Java versions. - Looking back.
AdjacentRepeats.javastarts ati = 1and counts words equal to the word before them (prints 3).
Misconception: A pair loop with the usual bound
Students write i < list.size() from habit. A list of n elements has n - 1 consecutive pairs, so the last valid i for get(i + 1) is size() - 2. Have students count the pairs in a small list on paper before writing the loop, and ask “What index does get(i + 1) reach on the last pass?”
Day 2 · Direct instruction: Duplicates
- Every pair, once (4.10.A.1, slide 11). Duplicate checks compare every element with every element after it: a nested loop (Topic 2.11) whose inner loop starts at
j = i + 1.Users.javaprintsrio. Strings are compared withequals. - Run
HasDuplicate.java(Match at 1 and 3,Has duplicate: true). Point to lines 19 and 20: each element is copied into anintbefore comparing with==. - Compare with itself. Show
DupSelfBug.java, whose inner loop starts atj = 0, and ask what it prints for 4, 8, 15. It printsHas duplicate: true, because ati = jevery element matches itself.DupSelfFixed.javastarts atj = i + 1and printsfalse. ==onInteger. RunIntegerEqualsBug.java: two 1000s are reported as different (Has duplicate: false), because==on twoIntegerobjects compares references (Topic 2.6).IntegerEqualsFixed.javaunboxes intointvariables first and printstrue. Small numbers may happen to work, which is why this bug hides in testing.
Misconception: The inner loop starts at 0
Students write the inner loop like the outer one. Then every element is compared with itself and the check always finds a “duplicate”. Starting at j = i + 1 skips the self-comparison and checks each pair once. Ask: “When i is 2, which j values do we still need?”
Misconception: == compares the values of Integer elements
list.get(i) == list.get(j) compares two Integer objects, so it asks whether they are the same object. Equal values in different objects compare as false. Unbox into int variables first, or for String elements use equals. The worksheet’s Watch out box after question 7 says the same.
Day 2 · Guided practice: Question 8
Pairs do worksheet question 8 (one-token fix). The duplicate check crashes because line 5’s inner loop runs j <= ids.size(). Change <= to < (or to !=), and the two 118s at indexes 1 and 3 match. Ask the pair who suggests changing ids.get(j) to ids.get(i) to test it with a list with no repeats: it still prints true, because every element then matches itself.
Day 2 · Direct instruction: Inserting while traversing
- Changing the list as you go (4.10.A.1, slides 12–13).
add(i, value)pushes the element ati, and everything after it, one place right. On slide 13 the loop inserts"stretch"before each"run", then an extrai++steps past the"run"that just moved. Output:[stretch, run, swim, stretch, run]. - Ask before you show: “Without the extra
i++, what does the loop do?” It finds the same"run"ati + 1, inserts again, and never ends. Do not run that version in class; describe it, or trace three passes on the board. - Run
InsertStudy.java(a"study"before every"test") andInsertAfterEven.java([3, 4, 0, 7, 8, 0]): inserting after the current element ati + 1also needs the extrai++, or the loop checks the new 0 next. - Insert in order. If time allows,
InsertInOrder.javaputs a value into a list that is already in order: find the first larger element andaddthere, or add at the end if there is none.
Misconception: Inserting without stepping past the new element
Students insert at i and let the loop’s i++ move on, expecting it to reach the next element. The element they were checking has moved to i + 1, so the loop lands on it again and inserts forever. Ask “Where is the element I just checked now?” after every insertion, and step i past it.
Day 2 · Closure: Closure
Ask: “After add(i, value), which way did the later elements move, and what did the loop have to do about it?” Students write: right, so add an extra i++.
Day 3 · Warm-up: Think First
Read the worksheet’s Think First box aloud: remove(1) on [10, 20, 30, 40]. Which value sits at index 1 afterward? Take a show of hands, then confirm: 30. The 20 is gone and 30 and 40 slide left. Tell students that this one fact explains today’s bug.
Day 3 · Direct instruction: Deleting while traversing
- Goal 4 (slide 3).
- Deleting forward skips an element (4.10.A.1, slide 14). Trace
Cleanup.javawith the slide’s table: ati = 0the first 0 is removed and the second 0 slides into index 0, but the loop’si++moves on to index 1, so that 0 is never checked. The program prints[0, 5]with no error. - Run
RemoveSkipBug.java. It is meant to remove every score below 60 from 55, 48, 90, 30, and prints[48, 90]: the 48 slid into the spot the loop had just checked. - Two fixes (slide 15). Fix 1 walks backward, so a removal moves only elements that were already checked. Fix 2 uses a
whileloop that adds 1 toionly when nothing was removed. Both print[5]. RunRemoveBackward.javaandRemoveForwardFixed.java(both[90]). - Not in an enhanced for loop. Run
RemoveEnhancedFor.java: the first removal changes the list’s size, and the next step of the loop throws aConcurrentModificationException(Topic 4.9). The same is true of adding. - Strings too.
RemoveShortWords.javaremoves words shorter than 3 letters with a backward loop and prints[cat, eagle].
Misconception: Every removal is checked because no error appeared
Students trust a forward delete because nothing crashes. Every index the loop uses is in range, so Java has nothing to report: the skipped element is a logic error. The worksheet’s Fair question box after question 5 says this directly. Test a delete with two matching elements side by side, which is the case that fails.
Misconception: Deleting inside an enhanced for loop
Students reach for the enhanced for loop because it is shorter. Changing the size of the list it is traversing throws a ConcurrentModificationException, even with a separate index counter. Any time the list’s size changes, use an indexed for or while loop.
Day 3 · Guided practice: Trace a backward delete
Show slide 16. Students fill in the table on mini whiteboards, starting at i = 4:
i |
nums.get(i) |
List after |
|---|---|---|
| 4 | 6 | [1, 3, 4, 5, 6] |
| 3 | 5 (odd) | [1, 3, 4, 6] |
| 2 | 4 | [1, 3, 4, 6] |
| 1 | 3 (odd) | [1, 4, 6] |
| 0 | 1 (odd) | [4, 6] |
The output is [4, 6]. Ask why the 3 was still checked after the 5 was removed: the removal moved only the 6, which the loop had already passed.
Day 3 · Independent practice: Independent practice
Students do worksheet questions 2, 3, and 5 alone:
- Question 2 (you’re the JVM): the forward delete prints
[emu, lion], choice B;emuandlioneach slide into a spot the loop just checked. - Question 3 (face-off): the blanks all come from which way the elements move.
- Question 5 (snippet pool):
scores.size() - 1,i >= 0,remove(i). Ask early finishers whyi > 0fails: index 0 (the 45) is never checked.
Unfinished questions are homework.
Day 3 · Direct instruction: Shift and rotate
- Goal 5 (slides 3 and 17).
removereturns what it removed (4.10.A.1, slide 18).line.add(line.remove(0));takes the first element off and puts it on the end: a rotate left,[Lu, Ty, Jo, Mo]. Thenremove(size() - 1)drops the last element andadd(0, "-")fills the front: a shift right,[-, Lu, Ty, Jo]. In a shift one element falls off; in a rotate it comes back at the other end.- Run
ShiftWindow.java(a shift left, then a shift right, both filling the empty end) andRotateTurns.java(a rotate left, then a rotate right, which restores the original order).
Day 3 · Closure: Closure
Ask: “What does remove(0) give back, and why does that make a rotate one line long?” It returns the element it removed, so it can be passed straight to add.
Day 4 · Warm-up: Question 6, snippets 1 and 5
Students do worksheet question 6, snippets 1 and 5 only, with nums holding [4, 7, 7, 2]. Snippet 1 is a rotate left ([7, 7, 2, 4]); snippet 5 is a shift right ([0, 4, 7, 7]). The rest of question 6 is homework.
Day 4 · Direct instruction: Reverse
- Swap pairs, stop halfway (4.10.A.1, slide 19). The partner of index
iislast - i. Each pass saves one value intemp, copies the partner over it withset, and putstempin the partner’s place. The loop stops ati < nums.size() / 2; the output is[6, 5, 4, 3, 2, 1]. - Odd lengths. Run
ReverseList.java([5, 4, 3, 2, 1]).5 / 2is 2 (integer division), so the middle element is never swapped, and it does not need to be. - Going all the way. Show
ReverseTwice.javaand ask for a prediction before running it. It prints[1, 2, 3, 4, 5], the original order: by the middle the list is reversed, and the second half of the loop swaps every pair back.
Misconception: A reverse loop that runs over the whole list
Students write i < nums.size() from habit. Every pair then gets swapped twice and the list ends where it started, with no error. A reverse touches two elements per pass, so it needs only half as many passes. Worksheet question 7’s lie is this exact claim.
Misconception: Swapping without a temporary variable
Students write nums.set(i, nums.get(last - i)); then nums.set(last - i, nums.get(i));. The first set has already overwritten element i, so both positions end up with the same value: SwapNoTemp.java turns 10 to 60 into [60, 50, 40, 40, 50, 60]. Save one value in temp first.
Day 4 · Direct instruction: Filtered lists and two collections
- Filtered list (4.10.A.1, slide 20). To keep only some elements, add the matches to a new list. The original stays whole. Run
BeforeM.java: fruits before"m"go intoearly([apple, kiwi, fig]), and the sizes5 3show thatfruitswas not changed. An enhanced for loop is fine here, because it adds to a different list. - The wrong list. Show
FilterAddBug.java, which adds tonumsinstead ofbig, and ask what happens. It throws aConcurrentModificationException;FilterAddFixed.javaprints[12, 15]. - Two collections, one index (4.10.A.2, slide 20).
Supplies.javawalks aString[]of items and anArrayList<Double>of prices with the samei, soprices.get(i)anditems[i]belong to the same item. The loop is bounded byprices.size(), the shorter collection: tape has no price. Output[pen, ink]. - Run
HonorRoll.java(names in an array, GPAs in a list:[Ava, Cleo, Dev]) andQuizKey.java(aStringkey and a list of answers:Correct: 3,Missed: [2]). The three kinds of collections in 4.10.A.2 (String, array,ArrayList) all appear. - The wrong bound. Run
ShortAnswersBug.java: the loop is bounded by the key’s length, one longer than the answers, and the program crashes with anIndexOutOfBoundsExceptionafter three lines.ShortAnswersFixed.javausesanswers.size().
Misconception: Bounding a side-by-side loop by the wrong collection
Students pick whichever collection they thought of first. If the other one is shorter, get(i) or [i] runs past its end. Bound the loop by the shorter collection, or by Math.min(...) of the two sizes (Topic 1.11) when either could be shorter.
Teacher note
CleanReadings.java (the guide’s Putting it together program) combines a backward delete, an average, a filtered list, and a pair check in one program. Use it as an extension for students who finish early, or as a review at the start of Topic 4.11.
Day 4 · Independent practice: Independent practice
Students do worksheet questions 4 and 7 alone:
- Question 4 (code tiles): the decoy is the loop bounded by
names.length; Eli has no lap count, solaps.get(4)would throw. The output is[Ana, Cy, Dee]. - Question 7 (two truths and a lie): claim 3 is the lie. Running to
rainbow.size()swaps every pair back.
Homework: the rest of question 6 (snippet 2 throws a ConcurrentModificationException, snippet 3 an IndexOutOfBoundsException, and snippet 4 never ends) and question 9 (who am I?).
Day 4 · Closure: Closure
Slide 21: review the vocabulary together; ask students to give a one-line code example for “rotate” and “filtered list”. Then slide 22: partners finish the sentence starter, “add(i, value) moves elements right, so I step past the new element; remove(i) moves them left, so I don’t step past the element that arrived (or I walk backward).” Take two pairs’ answers aloud.
Day 4 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Question 1 checks deleting while traversing, question 2 a rotate built from remove and add, and question 3 choosing a correct “all” flag over consecutive pairs. Re-teach the weakest one with the matching slide (15, 18, or 10) at the start of Topic 4.11.