Skip to content

Course navigation

For teachersTopic 4.10 · Lesson kit

Implementing ArrayList Algorithms

  • 4 class periods
  • 45 minutes each
  • Objective 4.10.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    4 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
4 class periods of 45 minutes
Learning objectives
4.10.A
Essential knowledge
4.10.A.14.10.A.2
Materials
Projector and the List Surgery slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)IDE on every computerPrinted List Surgery 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-upsame algorithm, new container (slide 2)
  2. 0:05–0:2015 minDirect instructionsum, average, minimum, maximum (slides 3–6)
  3. 0:20–0:3010 minDirect instructionany, all, and how many (slide 7)
  4. 0:30–0:388 minGuided practiceis every battery charged? (slide 8)
  5. 0:38–0:435 minIndependent practiceworksheet question 1, first seven rows
  6. 0:43–0:452 minClosurehow does each one start?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upworksheet question 1, last row
  2. 0:05–0:1712 minDirect instructionconsecutive pairs (slides 9–10)
  3. 0:17–0:2912 minDirect instructionduplicates (slide 11)
  4. 0:29–0:356 minGuided practiceworksheet question 8
  5. 0:35–0:438 minDirect instructioninserting while traversing (slides 12–13)
  6. 0:43–0:452 minClosurewhich way did the elements move?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upthe worksheet's Think First
  2. 0:05–0:1712 minDirect instructiondeleting while traversing (slides 14–15)
  3. 0:17–0:258 minGuided practicetrace a backward delete (slide 16)
  4. 0:25–0:3510 minIndependent practiceworksheet questions 2, 3, and 5
  5. 0:35–0:438 minDirect instructionshift and rotate (slides 17–18)
  6. 0:43–0:452 minClosurewhat does remove return?

Day 445 minutes

  • Warm-up
  • Direct instruction
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upworksheet question 6, snippets 1 and 5
  2. 0:05–0:1510 minDirect instructionreverse (slide 19)
  3. 0:15–0:2510 minDirect instructionfiltered lists and two collections (slide 20)
  4. 0:25–0:3510 minIndependent practiceworksheet questions 4 and 7
  5. 0:35–0:405 minClosurevocabulary and insert or delete? (slides 21–22)
  6. 0:40–0:455 minExit ticket

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 remove and add.
  • 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.java and ExitSortedCheck.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

  1. Goals (slide 3). Read the five goals; Day 1 covers goal 1.
  2. The translation table (4.10.A.1, slides 4–5). Point to the table on slide 5: arr.length is list.size(), arr[i] is list.get(i), and arr[i] = v; is list.set(i, v);. Walk through Scores.java on the slide: one loop keeps a running total and a best-so-far, and prints Average: 86.0 and Best: 95. Ask: “What does scores.get(i) return, and how can we add it to an int?” It returns an Integer, which Java unboxes to an int (Topic 4.7).
  3. Run SumAverage.java (total 27000 steps, average 5400.0). Point to the cast on total, not on the division, and to the slide’s reminder: an average divides by size(), so the list must not be empty. That is a precondition.
  4. Minimum and maximum together. Run MinMaxTemps.java (Lowest: -8, Highest: 5): both start at temps.get(0), and the loop compares each element with both.
  5. Start at a real element (slide 6). Show Freezer.java and 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 run MaxStartZero.java (Highest: 0) and MaxStartFirst.java (Highest: -2).
  6. Not only numbers. LongestWord.java keeps the longest String so far by comparing length() values and prints banana. 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

  1. Three questions, three starts (4.10.A.1, slide 7). Read the table on the slide: “any?” starts false and changes when one element has the property; “all?” starts true and changes when one element lacks it; “how many?” starts at 0 and adds 1 per match. Trace Rides.java with the class: 47 makes anyShort true, no height is below 42 so allTall stays true, and 52 and 60 are the two heights at least 50.
  2. Run GradeChecks.java (Any below 70: true, All passing: true, A grades: 2) and ask students to predict each line first.
  3. One loop, two jobs. TagChecks.java uses one if/else: a hashtag adds to the count, and anything else sets allTags to false. CountRange.java counts values from 10 to 20 with && (Topic 2.5) and sets an “over 50” flag in the same loop (3 true).
  4. 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

  1. Goal 2 (slides 3 and 9). Today is two elements at a time.
  2. 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() - 1 so that get(i + 1) stays in range; the program prints Drops: 2 (135 to 130 and 150 to 145). The other correct form starts at i = 1 and compares get(i - 1) with get(i).
  3. Run ConsecutiveRises.java (Rises: 3, Biggest jump: 5): the pair loop also keeps a maximum of the differences.
  4. Go one step too far. Show PairsTooFar.java and ask what happens with i < prices.size(). Run it: four pairs print, then an IndexOutOfBoundsException at i = 4, when get(5) is asked for. Mention that the exact message wording can vary between Java versions.
  5. Looking back. AdjacentRepeats.java starts at i = 1 and 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

  1. 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.java prints rio. Strings are compared with equals.
  2. Run HasDuplicate.java (Match at 1 and 3, Has duplicate: true). Point to lines 19 and 20: each element is copied into an int before comparing with ==.
  3. Compare with itself. Show DupSelfBug.java, whose inner loop starts at j = 0, and ask what it prints for 4, 8, 15. It prints Has duplicate: true, because at i = j every element matches itself. DupSelfFixed.java starts at j = i + 1 and prints false.
  4. == on Integer. Run IntegerEqualsBug.java: two 1000s are reported as different (Has duplicate: false), because == on two Integer objects compares references (Topic 2.6). IntegerEqualsFixed.java unboxes into int variables first and prints true. 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

  1. Changing the list as you go (4.10.A.1, slides 12–13). add(i, value) pushes the element at i, and everything after it, one place right. On slide 13 the loop inserts "stretch" before each "run", then an extra i++ steps past the "run" that just moved. Output: [stretch, run, swim, stretch, run].
  2. Ask before you show: “Without the extra i++, what does the loop do?” It finds the same "run" at i + 1, inserts again, and never ends. Do not run that version in class; describe it, or trace three passes on the board.
  3. Run InsertStudy.java (a "study" before every "test") and InsertAfterEven.java ([3, 4, 0, 7, 8, 0]): inserting after the current element at i + 1 also needs the extra i++, or the loop checks the new 0 next.
  4. Insert in order. If time allows, InsertInOrder.java puts a value into a list that is already in order: find the first larger element and add there, 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

  1. Goal 4 (slide 3).
  2. Deleting forward skips an element (4.10.A.1, slide 14). Trace Cleanup.java with the slide’s table: at i = 0 the first 0 is removed and the second 0 slides into index 0, but the loop’s i++ moves on to index 1, so that 0 is never checked. The program prints [0, 5] with no error.
  3. 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.
  4. Two fixes (slide 15). Fix 1 walks backward, so a removal moves only elements that were already checked. Fix 2 uses a while loop that adds 1 to i only when nothing was removed. Both print [5]. Run RemoveBackward.java and RemoveForwardFixed.java (both [90]).
  5. 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 a ConcurrentModificationException (Topic 4.9). The same is true of adding.
  6. Strings too. RemoveShortWords.java removes 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; emu and lion each 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 why i > 0 fails: index 0 (the 45) is never checked.

Unfinished questions are homework.

Day 3 · Direct instruction: Shift and rotate

  1. Goal 5 (slides 3 and 17).
  2. remove returns 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]. Then remove(size() - 1) drops the last element and add(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.
  3. Run ShiftWindow.java (a shift left, then a shift right, both filling the empty end) and RotateTurns.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

  1. Swap pairs, stop halfway (4.10.A.1, slide 19). The partner of index i is last - i. Each pass saves one value in temp, copies the partner over it with set, and puts temp in the partner’s place. The loop stops at i < nums.size() / 2; the output is [6, 5, 4, 3, 2, 1].
  2. Odd lengths. Run ReverseList.java ([5, 4, 3, 2, 1]). 5 / 2 is 2 (integer division), so the middle element is never swapped, and it does not need to be.
  3. Going all the way. Show ReverseTwice.java and 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

  1. 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 into early ([apple, kiwi, fig]), and the sizes 5 3 show that fruits was not changed. An enhanced for loop is fine here, because it adds to a different list.
  2. The wrong list. Show FilterAddBug.java, which adds to nums instead of big, and ask what happens. It throws a ConcurrentModificationException; FilterAddFixed.java prints [12, 15].
  3. Two collections, one index (4.10.A.2, slide 20). Supplies.java walks a String[] of items and an ArrayList<Double> of prices with the same i, so prices.get(i) and items[i] belong to the same item. The loop is bounded by prices.size(), the shorter collection: tape has no price. Output [pen, ink].
  4. Run HonorRoll.java (names in an array, GPAs in a list: [Ava, Cleo, Dev]) and QuizKey.java (a String key and a list of answers: Correct: 3, Missed: [2]). The three kinds of collections in 4.10.A.2 (String, array, ArrayList) all appear.
  5. 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 an IndexOutOfBoundsException after three lines. ShortAnswersFixed.java uses answers.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, so laps.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.

Exit ticket

Question 1 · Multiple choice

This program should remove every level below 50. Which statement is correct?

ExitDropLow.java
import java.util.ArrayList;

public class ExitDropLow
{
    public static void main(String[] args)
    {
        ArrayList<Integer> levels = new ArrayList<Integer>();
        levels.add(30);
        levels.add(20);
        levels.add(70);
        levels.add(10);
        levels.add(80);

        for (int i = 0; i < levels.size(); i++)
        {
            if (levels.get(i) < 50)
            {
                levels.remove(i);
            }
        }
        System.out.println(levels);
    }
}
  1. It prints [20, 70, 80]; traversing backward, from levels.size() - 1 down to 0, fixes it.
  2. It prints [70, 80]: the program already works.
  3. It prints [20, 70, 80]; switching to an enhanced for loop that removes each level below 50 fixes it.
  4. It throws an IndexOutOfBoundsException, because the test keeps using the size the list had when the loop started.
Check your reasoning

A.

i levels.get(i) List after
0 30 (removed) [20, 70, 10, 80]
1 70 [20, 70, 10, 80]
2 10 (removed) [20, 70, 80]

Then 3 < 3 is false and the loop ends. When 30 is removed, 20 slides into index 0, but the loop’s i++ moves on to index 1, so 20 is never checked. Going backward, a removal shifts only elements the loop has already checked, and the program prints [70, 80].

B misses the shift: after a removal, the next element slides into the index just checked and is skipped. C is not a fix: removing inside an enhanced for loop throws a ConcurrentModificationException. D thinks the test is worked out once, but levels.size() is called on every pass and sees the shorter list.

Question 2 · Multiple choice

line is an ArrayList<String> holding [a, b, c, d]. What does it hold after this statement runs?

line.add(0, line.remove(line.size() - 1));

  1. [b, c, d, a]
  2. [d, b, c, a]
  3. [d, a, b, c]
  4. An IndexOutOfBoundsException is thrown.
Check your reasoning

C. The argument runs first: line.remove(3) takes d off the end and returns it, leaving [a, b, c]. Then add(0, "d") puts it at the front and pushes the others right. This is a rotate right.

A is a rotate left, which would be line.add(line.remove(0));. B swaps the first and last elements, which needs set, not remove and add. D is wrong because every index used is valid: 3 is the last index of the 4-element list, and index 0 is always a valid place to insert.

Question 3 · Multiple choice

times is an ArrayList<Integer> with at least one element. Which code segment sets inOrder to true if every element is less than or equal to the element after it, and to false otherwise?

  1. boolean inOrder = true; for (int i = 0; i < times.size(); i++) { if (times.get(i) > times.get(i + 1)) { inOrder = false; } }
  2. boolean inOrder = true; for (int i = 0; i < times.size() - 1; i++) { if (times.get(i) > times.get(i + 1)) { inOrder = false; } }
  3. boolean inOrder = false; for (int i = 0; i < times.size() - 1; i++) { if (times.get(i) <= times.get(i + 1)) { inOrder = true; } }
  4. boolean inOrder = true; for (int i = 0; i < times.size() - 1; i++) { if (times.get(i) > times.get(i + 1)) { inOrder = false; } else { inOrder = true; } }
Check your reasoning

B. It is an “all” check: inOrder starts true, the loop visits consecutive pairs with a bound of i < times.size() - 1 so get(i + 1) is always a valid index, and it sets inOrder to false when an element is greater than the next one. Nothing sets it back to true. With the list 8, 9, 9, 12, 11, which drops at the last pair:

ExitSortedCheck.java
import java.util.ArrayList;

public class ExitSortedCheck
{
    public static void main(String[] args)
    {
        ArrayList<Integer> times = new ArrayList<Integer>();
        times.add(8);
        times.add(9);
        times.add(9);
        times.add(12);
        times.add(11);

        boolean inOrder = true;
        for (int i = 0; i < times.size() - 1; i++)
        {
            if (times.get(i) > times.get(i + 1))
            {
                inOrder = false;
            }
        }
        System.out.println("In order: " + inOrder);
    }
}
In order: false

A uses the bound i < times.size(), so on the last pass get(i + 1) throws an IndexOutOfBoundsException. C is an “any” check: it reports true if even one pair is in order, so 8, 9, 9, 12, 11 gives true. D sets the flag back to true on every pair that is in order, so only the last pair counts: 9, 8, 10 gives true.