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
- Goals (slide 3). Goals 1–2 are today’s, 3 is Day 2’s, and 4–5 are Day 3’s.
- 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.
ArrayListis in thejava.utilpackage, so the file needsimport java.util.ArrayList;at the top: every class used so far (String,Math,Integer) was injava.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. - Live demo: forget the import. Run
MissingImport.java, which is the same program without line 1. The compiler reportscannot find symbolforclass ArrayList, once for each use. Ask: “Which line fixes both errors?” - The element type must be a class (4.8.A.3, slide 6). The type parameter
EinArrayList<E>names the element type, and it must be a class, so a list of numbers isArrayList<Integer>orArrayList<Double>. RunIntList.java(ArrayList<int>) to show theunexpected typeerror. Then the payoff of writing the type: becauseaddtakes anEandgetreturns anE, the compiler catches a wrong element before the program runs. RunWrongType.java: line 9 tries to add42to a list ofStrings and line 10 stores aStringin anint; both are compiler errors. Autoboxing (Topic 4.7) is whyprices.add(2.5)works for anArrayList<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
- 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 returnstrue;size()returns the number of elements;get(index)returns the element at that index and leaves the list alone. Theprintln(list.add("jam"))line is there to show thetrue: most programs ignore it. Cross the first warm-up problem off the board: the fifth party is oneaddcall. - 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. size()is not a valid index (slide 9). With 3 elements, index 3 does not exist. RunGetPastEnd.java: it compiles, printsbreadfrom line 11, and then line 12 throws anIndexOutOfBoundsException. Ask: “Why couldn’t the compiler catch this one?” The list’s size is only known while the program runs. Connect it to theArrayIndexOutOfBoundsExceptionfrom 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
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 tosize()(inserting atsize()is the same as appending).add(index, obj)returns nothing (void).- Live demo. Run
InsertMiddle.java: Dev is inserted at index 1 of[Ana, Ben, Cy]. Before running, ask whatline.get(2)prints now. Answer:Ben, because Ben scooted from 1 to 2. set(index, obj)replaces (slide 13). Nothing moves and the size stays the same; the element at the index is overwritten.setreturns the old element, soString old = colors.set(2, "pink");savesblue. Point to the comparison table on the slide: size+1vs. same, returns nothing vs. the old element, valid index 0 tosize()vs. 0 tosize() - 1. RunSetReplace.javato show the same in a chores list: it printsdry, then[wash, iron, fold], then3.- Side by side. Run
SetVsInsert.java. Both calls take index 1 and"Dev";setgives[Ana, Dev, Cy]andaddgives[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
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.removereturns the removed element, soString gone = pets.remove(1);savespup. After the removal,pets.get(1)iscub, which used to be at index 2. Cross the second warm-up problem off the board: Raj leaving is oneremovecall. RunRemoveShift.javafor the same pattern with the line from Day 2: Dev is removed and Ben scoots back to index 1.- Removing two elements. Show
RemoveTwoWrong.javawithout its output. A coach wants to drop Ben (index 1) and Dev (index 3) from[Ana, Ben, Cy, Dev, Eve]and writesremove(1)thenremove(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). removetakes an index, even for numbers (slide 17). In the Java Quick Reference, the method isremove(int index). In a list ofIntegers,nums.remove(2)removes whatever is at index 2, not the value 2. RunRemoveIndexNotValue.javafor a second case:nums.remove(1)on[40, 2, 7, 1]removes the2and leaves the1.
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
- 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. Sodesk.toggle()changes the oneLampthat bothdeskandroom.get(0)point to: the first line printstrue. Thendesk = new Lamp();pointsdeskat a different object; the list still holds the old reference, so the second line printstrueand the third printsfalse. Draw the arrows on the board: two arrows into one lamp, then one arrow moves. - Live demo. Run
TeamRefs.java:kai.addPoints(5)shows up throughteam.get(0)(15), andteam.get(0).addPoints(3)shows up throughkai(18). Then runStringReassign.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.