Skip to content

Course navigation

For teachersTopic 4.8 · Lesson kit

ArrayList Methods

  • 3 class periods
  • 45 minutes each
  • Objective 4.8.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.8.A
Essential knowledge
4.8.A.14.8.A.24.8.A.34.8.A.44.8.A.54.8.A.6
Materials
Projector and the Scoot Over slide deckWhiteboard and markersSticky notes or index cards for the Day 1 closure and the Day 2 line-up demoIDE on every computer, or at least on the projectorPrinted Scoot Over 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-upthe waiting list (slide 2)
  2. 0:05–0:1813 minDirect instructionimport, empty list, element type (slides 3–6)
  3. 0:18–0:3012 minDirect instructionadd, size, get, and the valid indexes (slides 7–9)
  4. 0:30–0:355 minGuided practicewhich hat? (slide 10)
  5. 0:35–0:438 minIndependent practicepuzzle worksheet question 6
  6. 0:43–0:452 minClosuresize() versus the last index

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upretrieval on the board
  2. 0:05–0:2015 minDirect instructioninsert with add(index, obj), replace with set (slides 11–13)
  3. 0:20–0:277 minGuided practicetrack the list (slide 14)
  4. 0:27–0:4215 minIndependent practicepuzzle worksheet questions 4–5
  5. 0:42–0:453 minClosuremake room or overwrite?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upset or insert?
  2. 0:05–0:1712 minDirect instructionremove and the shift left (slides 15–17)
  3. 0:17–0:258 minDirect instructiona list holds references (slide 18)
  4. 0:25–0:305 minGuided practiceremove, then replace (slide 19)
  5. 0:30–0:377 minIndependent practicepuzzle worksheet questions 1, 2, and 8
  6. 0:37–0:458 minClosurewho moved? (slides 20–21), then the exit ticket

Overview

Three class periods. Students meet their first collection that can change size. Day 1 builds an empty list and fills it: the import from java.util (4.8.A.4), the constructor that makes an empty list (4.8.A.2), the element type in angle brackets (4.8.A.3), and size, add(obj), and get with indexes from 0 to size() - 1 (4.8.A.5, 4.8.A.6). Day 2 is the core contrast of the topic: add(index, obj) makes room and shifts later elements right, while set overwrites and returns the old element. Day 3 removes elements, tracks the shift left, and closes with the fact that a list holds references to objects (4.8.A.1).

Keep one picture running through all three days: a row of numbered boxes in which the elements scoot over. Before any call with an index, students should ask, “Does this make room, overwrite, or close a gap?” and then redraw the row. The deck and worksheet use the same word, “scoot.”

Stay inside the topic boundary. Every list in this lesson is built and read one call at a time. Looping over a list is Topic 4.9, and removing inside a loop comes with it, so do not use a for or while loop with a list, even though students know loops from Unit 2. The wrapper classes and autoboxing are Topic 4.7 and can be assumed. Arrays (Topics 4.3 to 4.5) are the comparison point throughout.

Teacher note

The slides are the Scoot Over deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–10, Day 2 slides 11–14, and Day 3 slides 15–21. The Scoot Over puzzle worksheet has 10 questions and takes about 30 minutes. Each question needs only the methods taught so far, so assign it by day: question 6 on Day 1; questions 4, 5, and 9 on Day 2 (question 9 names all six methods, so leave its last clue, remove, for Day 3 if students ask); questions 1, 2, 3, 7, 8, and 10 on Day 3.

The topic’s examples/ folder has a runnable file for every demonstration named below. Before Day 1, open MissingImport.java, IntList.java, WrongType.java, and GetPastEnd.java in the IDE; before Day 2, InsertMiddle.java, SetReplace.java, and SetVsInsert.java; before Day 3, RemoveShift.java, RemoveTwoWrong.java, RemoveTwoFixed.java, RemoveIndexNotValue.java, TeamRefs.java, and StringReassign.java.

Day 1 · Warm-up: The waiting list

Show slide 2. A restaurant keeps its waiting list in a String[] of length 4: Pia, Raj, Tam, Uma. A fifth party walks in, then Raj leaves. Partners decide what they would have to do to the array. Take answers and write the two problems on the board: the fifth name has nowhere to go, because an array’s length is fixed when it is created (Topic 4.3); and when Raj leaves, the array is left with a gap, or someone has to copy Tam and Uma one box to the left by hand.

Say: “Today’s class does both jobs in one method call each.” Leave the two problems on the board; you will cross them off on Days 1 and 3.

Day 1 · Direct instruction: Import, empty list, element type

  1. Goals (slide 3). Goals 1–2 are today’s, 3 is Day 2’s, and 4–5 are Day 3’s.
  2. Making an empty list (4.8.A.1, 4.8.A.2, 4.8.A.4, slides 4–5). Walk the three labels on slide 5. ArrayList is in the java.util package, so the file needs import java.util.ArrayList; at the top: every class used so far (String, Math, Integer) was in java.lang, which needs no import. ArrayList<String> is the type of the variable. new ArrayList<String>() calls the constructor, which always builds an empty list: size() is 0, and printing the list shows []. Stress the phrase mutable in size: unlike an array, the list grows and shrinks after it is created.
  3. Live demo: forget the import. Run MissingImport.java, which is the same program without line 1. The compiler reports cannot find symbol for class ArrayList, once for each use. Ask: “Which line fixes both errors?”
  4. The element type must be a class (4.8.A.3, slide 6). The type parameter E in ArrayList<E> names the element type, and it must be a class, so a list of numbers is ArrayList<Integer> or ArrayList<Double>. Run IntList.java (ArrayList<int>) to show the unexpected type error. Then the payoff of writing the type: because add takes an E and get returns an E, the compiler catches a wrong element before the program runs. Run WrongType.java: line 9 tries to add 42 to a list of Strings and line 10 stores a String in an int; both are compiler errors. Autoboxing (Topic 4.7) is why prices.add(2.5) works for an ArrayList<Double> on the slide.

Misconception: Forgetting the import

Students have written dozens of programs with no import, because String, Math, and the wrapper classes are in java.lang. The cannot find symbol message names the class, which is the clue. Make “first line: import java.util.ArrayList;” part of every list program for the rest of the unit; the worksheet’s directions assume it.

Misconception: A list of ints is ArrayList<int>

Students write the primitive type they want to store. The element type must be a class, so the wrapper class goes in the angle brackets: ArrayList<Integer>, ArrayList<Double>. Autoboxing still lets them write scores.add(88) and int first = scores.get(0). Ask: “What goes in the brackets: a primitive or a class?”

Day 1 · Direct instruction: Add, size, get, and the valid indexes

  1. Append, count, and look (4.8.A.5, slides 7–8). Cover the output on slide 8 and have students predict it line by line before you reveal it. add(obj) appends to the end and returns true; size() returns the number of elements; get(index) returns the element at that index and leaves the list alone. The println(list.add("jam")) line is there to show the true: most programs ignore it. Cross the first warm-up problem off the board: the fifth party is one add call.
  2. Indexes start at 0 (4.8.A.6). The first element is at index 0 and the last at size() - 1, exactly as with arrays. list.get(list.size() - 1) is the safe way to say “the last element” no matter how long the list is.
  3. size() is not a valid index (slide 9). With 3 elements, index 3 does not exist. Run GetPastEnd.java: it compiles, prints bread from line 11, and then line 12 throws an IndexOutOfBoundsException. Ask: “Why couldn’t the compiler catch this one?” The list’s size is only known while the program runs. Connect it to the ArrayIndexOutOfBoundsException from Topic 4.3.

Misconception: Writing length for a list

Arrays use length (no parentheses) and strings use length(), so students try both on a list. Neither compiles: a list has only size(). The vocabulary slide (slide 20) and worksheet question 6, snippet 5, both target this. Ask students to say the three forms aloud: array length, String length(), list size().

Misconception: Index size() is the last element

“The list has 3 elements, so the last one is number 3.” Draw the boxes with their indexes under them every time, as on slide 9. The last index is always one less than the size, and any index outside 0 to size() - 1 crashes get.

Day 1 · Guided practice: Which hat?

Slide 10. Students write the exact output on their own for one minute, compare with a partner, then share. Answer: beanie 3 and beanie. The list is [cap, beanie, fedora]; get(1) is beanie and size() is 3; hats.size() - 2 is 1, so the second line is beanie again. Ask which index would crash (3 or higher) and how to print fedora without knowing the size (hats.get(hats.size() - 1)).

Day 1 · Independent practice: Independent practice

Worksheet question 6 (You’re the Compiler). Students decide for each snippet whether it compiles, then what it prints or which exception it throws. Every snippet uses only today’s material. Circulate and check snippet 4, which is the one students most often call a compiler error: words.get(1) compiles because 1 is a legal int, and fails only at run time because the list has just index 0.

Teacher note

Students keep the worksheet for the rest of the topic. Anything of question 6 not finished in class is homework.

Day 1 · Closure: Closure

Ask: “A list has 7 elements. What does size() return, what is the last index, and what happens with get(7)?” Students answer on a sticky note: 7, 6, an IndexOutOfBoundsException when the program runs.

Day 2 · Warm-up: Retrieval on the board

Write on the board, without running it: a list built with add("Ana"), add("Ben"), add("Cy"). Ask for size(), get(0), the last index, and the expression for the last element that works for any size. Then ask: “How would you put Dev between Ana and Ben?” Most students can only answer with arrays in mind (shift by hand). That is the question Day 2 answers.

Day 2 · Direct instruction: Insert with add(index, obj), replace with set

  1. add(index, obj) inserts and scoots (4.8.A.5, slides 11–12). Act it out first: call four students to the front holding cards red, blue, green, and number their positions 0–2 with sticky notes on the board behind them. A fourth student with gold steps in at index 1; blue and green each move one place right, and their numbers go up by 1. Then show slide 12. The rule: everything from the index on moves right, the size goes up by 1, and the valid index runs from 0 to size() (inserting at size() is the same as appending). add(index, obj) returns nothing (void).
  2. Live demo. Run InsertMiddle.java: Dev is inserted at index 1 of [Ana, Ben, Cy]. Before running, ask what line.get(2) prints now. Answer: Ben, because Ben scooted from 1 to 2.
  3. set(index, obj) replaces (slide 13). Nothing moves and the size stays the same; the element at the index is overwritten. set returns the old element, so String old = colors.set(2, "pink"); saves blue. Point to the comparison table on the slide: size +1 vs. same, returns nothing vs. the old element, valid index 0 to size() vs. 0 to size() - 1. Run SetReplace.java to show the same in a chores list: it prints dry, then [wash, iron, fold], then 3.
  4. Side by side. Run SetVsInsert.java. Both calls take index 1 and "Dev"; set gives [Ana, Dev, Cy] and add gives [Ana, Dev, Ben, Cy]. Give students the question that decides between them: “Should the element at this index still be in the list afterward?”

Misconception: set and add(index, obj) do the same thing

Both take an index and an element, so students pick either one. One overwrites and one makes room. Use the question above, and have students write the size afterward next to every call, because the size is the quickest check: set never changes it.

Misconception: Using set to add a new element at the end

With three elements, set(3, x) looks like “put x in the next spot,” but set can only replace an element that exists, so it throws an IndexOutOfBoundsException. add(3, x) works, because inserting may use index size(), and add(x) is simpler still. Worksheet question 5 ends on exactly this contrast.

Misconception: set returns the new element (or true)

Students expect set to return what they just put in, or true like add(obj). It returns the element that was at the index. Have students label every call’s return value as you trace: add(obj) returns true, add(index, obj) returns nothing, set returns the old element.

Day 2 · Guided practice: Track the list

Slide 14. Students draw the list after every line, using the slide’s hint for each call with an index: “Does this make room, or overwrite?” Then they say what prints. Give three minutes, then trace it together on the board:

Line Call c afterward
3 add("x") [x]
4 add("y") [x, y]
5 add(0, "w") [w, x, y]
6 set(1, "v") [w, v, y]
7 add(c.size(), "z") [w, v, y, z]

Output: [w, v, y, z] and 4. Discuss line 6 (the x is gone: set overwrote it) and line 7 (index size() is legal for inserting and means “at the end”).

Day 2 · Independent practice: Independent practice

Worksheet questions 4 (snippet pool) and 5 (face-off). In question 4, the two inserts must run in the right order, so watch for students who choose add(2, "Lily") first; ask them to redraw the list after each hole. Question 5 is a fill-in summary of today’s comparison table. Question 9 (who am I?) is homework; students can leave its last clue for Day 3.

Day 2 · Closure: Closure

Each student writes one line of code that makes room and one that overwrites, both at index 1 of a list named names, and labels the size change of each. Collect a few and read them aloud.

Day 3 · Warm-up: Set or insert?

On the board: a list [Ana, Ben, Cy]. Ask for the list and the size after set(1, "Dev") and, separately, after add(1, "Dev"). Answers: [Ana, Dev, Cy], size 3; [Ana, Dev, Ben, Cy], size 4. Then point to the second warm-up problem still on the board from Day 1: Raj leaves the waiting list. Today’s first method handles it.

Day 3 · Direct instruction: Remove and the shift left

  1. remove(index) closes the gap (4.8.A.5, slides 15–16). The element at the index is taken out, every later element moves left (its index goes down by 1), and the size goes down by 1. remove returns the removed element, so String gone = pets.remove(1); saves pup. After the removal, pets.get(1) is cub, which used to be at index 2. Cross the second warm-up problem off the board: Raj leaving is one remove call. Run RemoveShift.java for the same pattern with the line from Day 2: Dev is removed and Ben scoots back to index 1.
  2. Removing two elements. Show RemoveTwoWrong.java without its output. A coach wants to drop Ben (index 1) and Dev (index 3) from [Ana, Ben, Cy, Dev, Eve] and writes remove(1) then remove(3). Students predict, then run it: [Ana, Cy, Dev]. Eve was removed, because after the first call Dev had moved to index 2. Show the two fixes: use the index from the list as it is at that moment (remove(2)), or remove the higher index first (RemoveTwoFixed.java).
  3. remove takes an index, even for numbers (slide 17). In the Java Quick Reference, the method is remove(int index). In a list of Integers, nums.remove(2) removes whatever is at index 2, not the value 2. Run RemoveIndexNotValue.java for a second case: nums.remove(1) on [40, 2, 7, 1] removes the 2 and leaves the 1.

Misconception: Using indexes from before an earlier insert or remove

Students look up every index in the original list and then make several calls. After any add(index, obj) or remove(index), every later element has a new index. Make students redraw the list after each call, and offer the shortcut for removing several elements: remove the highest index first, because it moves nothing before it. Worksheet question 8 is this exact bug.

Misconception: remove removes the value I pass

In a list of numbers, remove(30) reads like “remove the 30.” The argument is always a position. If the list is shorter than 31, it throws an IndexOutOfBoundsException; if it is long enough, it quietly removes the wrong element. Worksheet question 7’s lie is this claim.

Day 3 · Direct instruction: A list holds references

  1. A list holds references (4.8.A.1, slide 18). room.add(desk) stores a copy of the reference, not a copy of the lamp. So desk.toggle() changes the one Lamp that both desk and room.get(0) point to: the first line prints true. Then desk = new Lamp(); points desk at a different object; the list still holds the old reference, so the second line prints true and the third prints false. Draw the arrows on the board: two arrows into one lamp, then one arrow moves.
  2. Live demo. Run TeamRefs.java: kai.addPoints(5) shows up through team.get(0) (15), and team.get(0).addPoints(3) shows up through kai (18). Then run StringReassign.java: item = "oat milk" changes only the variable, so the list still prints [milk]. The only way to change what the list holds is a list method: groceries.set(0, "oat milk").

Misconception: Reassigning a variable changes the list

Students see room.add(desk) and think of desk and the list as one thing. Calling a method on the object (desk.toggle()) changes the object, which the list also refers to. Assigning a new object to the variable (desk = new Lamp()) changes only the variable. Ask of each line: “Does this change an object, or move an arrow?”

Day 3 · Guided practice: Remove, then replace

Slide 19. Students draw the list after each line and say what prints; the hint reminds them that the argument q.remove(1) runs before set does. Answer: line 7 removes cub, leaving [kit, pup, joey]; on line 8, q.remove(1) removes and returns pup, leaving [kit, joey], and then set(0, "pup") replaces kit. Output: [pup, joey] and 2.

Day 3 · Independent practice: Independent practice

In class, students work worksheet questions 1 (set and remove return values), 2 (the pencil-check table; the Think First note before it asks the Day 2 insert question again), and 8 (the one-token fix from the removal demo). Questions 3 (code tiles: a carpool that rotates with remove(0) and add), 7 (two truths and a lie), 9 if unfinished, and 10 (a list of Frog objects) are homework, about 15 minutes.

Teacher note

Question 3 uses the value returned by remove(0) and adds it back at the end; it is a good stretch for students who finish questions 1, 2, and 8 early. Question 10 is the worksheet’s references question; if Day 3 runs short, make sure it is in the homework, since the exit ticket does not test references.

Day 3 · Closure: Closure and exit ticket

Spend one minute on slide 20 (vocabulary). Then slide 21: partners explain what happens to the name at index 3 of a 5-name list after remove(1), using the sentence starter. Expected answer: it is now at index 2, because removing index 1 moves every later element one place left. Then give the exit ticket (about five minutes). Question 1 checks insert, set’s return value, and remove in one trace; question 2 checks the index shift after a removal; question 3 checks the element type and that remove takes an index (which lines compile, and what the one that does compile does when it runs). Re-teach the weakest one at the start of Topic 4.9.

Exit ticket

Question 1 · Multiple choice

ExitLineUp.java
import java.util.ArrayList;

public class ExitLineUp
{
    public static void main(String[] args)
    {
        ArrayList<String> line = new ArrayList<String>();
        line.add("Ann");
        line.add("Bo");
        line.add("Cal");
        line.add(1, "Dee");
        String x = line.set(2, "Eli");
        line.remove(0);
        System.out.println(x + " " + line);
    }
}

What does this program print?

  1. Eli [Dee, Eli, Cal]
  2. Cal [Dee, Eli]
  3. Bo [Dee, Eli, Cal]
  4. true [Dee, Eli, Cal]
Check your reasoning

C. After the three appends the list is [Ann, Bo, Cal]. add(1, "Dee") inserts and shifts Bo and Cal right: [Ann, Dee, Bo, Cal]. set(2, "Eli") replaces Bo and returns the old element, so x is "Bo": [Ann, Dee, Eli, Cal]. remove(0) takes out Ann and shifts the rest left: [Dee, Eli, Cal].

A thinks set returns the new element. B treats add(1, "Dee") as a replacement, so Bo is lost, set(2, ...) then replaces Cal, and one element too few remains. D confuses set with add(obj), which returns true.

Question 2 · Multiple choice

ExitRemoveTwo.java
import java.util.ArrayList;

public class ExitRemoveTwo
{
    public static void main(String[] args)
    {
        ArrayList<String> crew = new ArrayList<String>();
        crew.add("Ike");
        crew.add("Jo");
        crew.add("Kim");
        crew.add("Lu");
        crew.add("Max");
        crew.remove(1);
        crew.remove(3);
        System.out.println(crew);
    }
}

The programmer wants to remove Jo and Lu, leaving [Ike, Kim, Max]. Which statement is correct?

  1. It prints [Ike, Kim, Max]: line 14 removes Lu, so the program already works.
  2. It throws an IndexOutOfBoundsException on line 14, because the list has only 4 elements after line 13.
  3. It prints [Ike, Kim, Lu]; changing line 14 to crew.remove(4); fixes it.
  4. It prints [Ike, Kim, Lu]; changing line 14 to crew.remove(2); fixes it.
Check your reasoning

D. Line 13 removes Jo (index 1), and every later element shifts left: [Ike, Kim, Lu, Max]. Lu is now at index 2, so line 14’s remove(3) removes Max, and the program prints [Ike, Kim, Lu]. crew.remove(2); removes Lu. (Removing the higher index first, crew.remove(3); then crew.remove(1);, also works, because removing index 3 does not move anything before it.)

A uses the indexes the elements had before line 13, but a removal moves every later element down by 1. B mixes up the size with the last index: a 4-element list has indexes 0 to 3, so remove(3) is valid. C shifts the elements the wrong way: they move left after a removal, and index 4 does not exist in a 4-element list, so remove(4) throws an IndexOutOfBoundsException.

Question 3 · Multiple choice

nums is an ArrayList<Integer> that holds [4, 8, 15]. Which statement about these three lines is correct?

  1. ArrayList<int> counts = new ArrayList<int>();
  2. nums.add("16");
  3. nums.remove(8);
  1. Only line 3 compiles, and it throws an IndexOutOfBoundsException when it runs.
  2. Only line 3 compiles, and it removes the 8, leaving [4, 15].
  3. Lines 2 and 3 compile: line 2 adds the number 16 to the end of nums.
  4. Lines 1 and 3 compile: line 1 makes an empty list that holds int values.
Check your reasoning

A. Line 1 does not compile, because the element type must be a class: a list of whole numbers is ArrayList<Integer>. Line 2 does not compile, because "16" is a String and add on an ArrayList<Integer> takes an Integer. Line 3 compiles, but the argument to remove is always an index, not a value. The valid indexes are 0 to 2, so remove(8) throws an IndexOutOfBoundsException when it runs. To remove the 8, write nums.remove(1);.

B treats the argument to remove as the value to find, but it is an index. C expects Java to turn the String "16" into a number; the element type lets the compiler reject it before the program runs. D uses a primitive type as the element type, but an ArrayList holds only objects.