ArrayList - Complete Interactive Lesson
Part 1: Core Concepts
📋 ArrayList Algorithms
Part 1 of 7 — Removing, Searching, and Common Patterns
The Remove-While-Traversing Trap
// BUGGY: Skips elements after removal!
ArrayList<String> words = new ArrayList<>();
// words = ["cat", "cat", "dog", "bird"]
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("cat")) {
words.remove(i);
// After removing index 0: ["cat", "dog", "bird"]
// i becomes 1, so the "cat" now at index 0 is never checked!
}
}
Three Correct Solutions
// Solution 1: Decrement i after removal
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals("cat")) {
words.remove(i);
i--; // Recheck this index
}
}
// Solution 2: Traverse backward
for (int i = words.size() - 1; i >= 0; i--) {
if (words.get(i).equals("cat")) {
words.remove(i); // Removal does not affect earlier indices
}
}
// Solution 3: Use while loop
int i = 0;
while (i < words.size()) {
if (words.get(i).equals("cat")) {
words.remove(i); // Do NOT increment i
} else {
i++;
}
}
🔑 Backward traversal is the safest and simplest approach for removing elements, since removing a later element does not affect the indices of earlier ones.
Concept Check 🎯
Common ArrayList Algorithms
Finding the Maximum
public int findMax(ArrayList<Integer> list) {
int max = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) > max) {
max = list.get(i);
}
}
return max;
}
Removing All Occurrences
public void removeAll(ArrayList<String> list, String target) {
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).equals(target)) {
list.remove(i);
}
}
}
Building a Filtered List
public ArrayList<Integer> getEvens(ArrayList<Integer> list) {
ArrayList<Integer> evens = new ArrayList<>();
for (int val : list) {
if (val % 2 == 0) {
evens.add(val);
}
}
return evens;
}
Removing Duplicates
public ArrayList<String> removeDups(ArrayList<String> list) {
ArrayList<String> result = new ArrayList<>();
for (String s : list) {
boolean seen = false;
for (String r : result) {
if (r.equals(s)) {
seen = true;
}
}
if (!seen) {
result.add(s);
}
}
return result;
}
There is no membership method on the AP Java Quick Reference, so the inner loop does the search by hand: it walks the result list and sets a flag when it finds an equal String.
Applied Recall ✍️
-
When removing elements from an ArrayList in a forward loop, you must _______ the index after each removal to avoid skipping.
-
The safest way to remove elements while traversing is to iterate _______.
-
To test whether two String elements of a list hold the same characters, call the _______ method, not ==.
Choose the Pattern 🔍
AP Exam Strategy: ArrayList Algorithms
- The remove-while-traversing bug is one of the most commonly tested topics
- Always compare Strings with
.equals(), never== - Know three solutions: backward loop, i-- after remove, while loop with conditional increment
- FRQ tip: if the question says "remove all X," traverse backward
- The enhanced for loop is read-only for modification purposes — do not add or remove
list.remove(i)returns the removed element — useful for moving elements between lists
AP-Style Application 🎯
Part 2: Standard Algorithms on ArrayLists
📋 ArrayList Algorithms
Part 2 of 7 — Standard Algorithms on ArrayLists
Part 1 handled the algorithm that is special to lists, removing while traversing, along with finding a maximum and filtering. This part writes the rest of the standard algorithm set for lists (CED Topic 4.10). They are the same algorithms you wrote for arrays, with size() and get(i) in place of length and arr[i].
🔑 Key Concept: The Java Quick Reference has no searching method for ArrayList. To find an element, count matches, or ask whether a value is present, you write the loop yourself.
| Algorithm | Loop | Result |
|---|---|---|
| Sum and average | enhanced for | a running total, then a double division |
| Minimum or maximum with its index | indexed for from 1 | the index of the best element so far |
| Count matches | enhanced for | a counter |
| First or last index of a target | indexed, forward or backward | the index, or -1 when it is absent |
| Is any / are all | enhanced for with an early return | a boolean |
| Compare neighbors | indexed for from 1 | uses get(i - 1) and get(i) |
| Find a duplicate | nested indexed loops, j from i + 1 | a boolean |
Sum and Average
public static double average(ArrayList<Integer> nums) {
int sum = 0;
for (int n : nums) {
sum += n;
}
return (double) sum / nums.size();
}
For [2, 3] this returns 2.5. Without the cast, sum / nums.size() is int division and gives 2, which becomes 2.0 when it is returned as a double. The method assumes the list has at least one element.
The Index of the Minimum
public static int indexOfMin(ArrayList<Integer> nums) {
int best = 0; // index of the smallest so far
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i) < nums.get(best)) {
best = i;
}
}
return best;
}
| i | nums.get(i) | nums.get(best) | best afterward |
|---|---|---|---|
| start | 0 (value 5) | ||
| 1 | 2 | 5 | 1 |
| 2 | 8 | 2 | 1 |
| 3 | 2 | 2 | 1: a tie does not replace |
For [5, 2, 8, 2] the method returns 1. Keeping an index instead of a value lets the caller get both: nums.get(best) is the smallest value. With <= in place of <, ties replace the best, so the method would return the last smallest index, 3.
Counting Matches
public static int countLonger(ArrayList<String> words, int n) {
int count = 0;
for (String w : words) {
if (w.length() > n) {
count++;
}
}
return count;
}
The counter starts at 0 before the loop and is returned after it. For [tree, at, river, sky] and n = 3, the count is 2.
Concept Check 🎯
Searching: First and Last Index
public static int firstIndexOf(ArrayList<String> list, String target) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(target)) {
return i;
}
}
return -1;
}
return iinside the loop stops the search at the first match.return -1after the loop runs only when nothing matched. Since -1 is never a valid index, the caller can test for it.- To find the last index, traverse backward, from
list.size() - 1down to 0, and return the first match you meet.
A membership test is then one line:
public static boolean has(ArrayList<String> list, String target) {
return firstIndexOf(list, target) != -1;
}
Is Any? Are All?
public static boolean allPositive(ArrayList<Integer> nums) {
for (int n : nums) {
if (n <= 0) {
return false; // one counterexample settles it
}
}
return true; // no counterexample anywhere
}
| Question | Return inside the loop | Return after the loop |
|---|---|---|
| Is any element a match? | true, at the first match | false |
| Are all elements matches? | false, at the first non-match | true |
The classic bug is an else branch that returns the opposite answer inside the loop. Then the method returns during the very first pass, after looking at only one element.
Neighbors and Duplicates
public static int countIncreases(ArrayList<Integer> readings) {
int count = 0;
for (int i = 1; i < readings.size(); i++) {
if (readings.get(i) > readings.get(i - 1)) {
count++;
}
}
return count;
}
Starting at 1 makes get(i - 1) safe on the first pass. For [4, 6, 5, 7, 9] the increases are 4 to 6, 5 to 7 and 7 to 9, so the method returns 3.
public static boolean hasDuplicate(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) {
return true;
}
}
}
return false;
}
Starting j at i + 1 compares each pair once and never compares an element with itself. A list of 4 distinct elements needs 3 + 2 + 1 = 6 comparisons before the method returns false.
Find the Behavior 🎯
Segment A
public static boolean allEven(ArrayList<Integer> nums) {
for (int n : nums) {
if (n % 2 != 0) {
return false;
} else {
return true;
}
}
return true;
}
Count It ✍️
-
hasDuplicate runs on a list of 5 distinct Strings. How many times does it call equals before it returns false?
-
What does countIncreases return for [3, 8, 2, 9, 9, 10]?
Part 3: Inserting and Removing in Place
📋 ArrayList Algorithms
Part 3 of 7 — Inserting and Removing in Place
Part 1 showed why a forward loop that removes elements skips the next one. This part generalizes that idea to every algorithm that changes the size of a list while walking through it (CED Topic 4.10): inserting at the right place, inserting next to matches, removing runs of repeats, and moving elements with the value that remove returns.
🔑 Key Concept: When the body of a forward loop inserts or removes, ask where the element you have not looked at yet is now, then set the index so that the next pass lands on it.
| In a forward loop, the body... | Next pass should look at | So the code... |
|---|---|---|
replaces with set(i, x) | i + 1 | lets the loop's i++ run |
| removes the element at i | i | does not advance (or uses i--) |
| inserts after the current element, at i + 1 | i + 2 | adds an extra i++ to skip the new element |
| inserts before the current element, at i | i + 2 | adds an extra i++, since the current element moved to i + 1 |
Inserting Into a Sorted List
// Precondition: nums is in increasing order
public static void insertSorted(ArrayList<Integer> nums, int value) {
int i = 0;
while (i < nums.size() && nums.get(i) < value) {
i++;
}
nums.add(i, value);
}
| Call on [2, 5, 9] | Where the while loop stops | List afterward |
|---|---|---|
insertSorted(nums, 6) | i = 2, at the 9 | [2, 5, 6, 9] |
insertSorted(nums, 12) | i = 3, the size | [2, 5, 9, 12]: index 3 appends |
insertSorted(nums, 1) | i = 0, at the 2 | [1, 2, 5, 9] |
insertSorted(nums, 5) | i = 1, at the 5 | [2, 5, 5, 9]: placed before the equal value |
The i < nums.size() test comes first, so when the value is larger than everything, the loop stops at the size and never calls get(nums.size()). Because add(index, obj) accepts the size as an index, the same add call handles the append case.
Inserting Next to Matches
// nums holds [3, -1, 4]: put a copy of every negative right after it
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) < 0) {
nums.add(i + 1, nums.get(i));
i++; // skip the copy just inserted
}
}
// nums is [3, -1, -1, 4]
| i at the test | Element | Action | nums afterward |
|---|---|---|---|
| 0 | 3 | none | [3, -1, 4] |
| 1 | -1 | insert -1 at 2, then skip to 2 | [3, -1, -1, 4] |
| 3 | 4 | none | [3, -1, -1, 4] |
Without the extra i++, the next pass would land on the copy, which is also negative, so the loop would insert another copy, and another, and never end.
Concept Check 🎯
Segment A (nums holds [-2, 5, -7])
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) < 0) {
nums.add(i, 0);
i++;
}
}
Removing Runs of Repeats
// letters holds [a, a, b, b, b, c, a]
int i = 1;
while (i < letters.size()) {
if (letters.get(i).equals(letters.get(i - 1))) {
letters.remove(i); // the next element slides into i: stay put
} else {
i++;
}
}
// letters is [a, b, c, a]
Each element is compared with the one just before it. A removal brings a new element to index i, so i stays put; only a non-match moves on. The last a survives, because it is not next to the first one.
Moving Elements With the Value remove Returns
remove(i) hands back the element it took out, so it can be added somewhere else in the same statement.
nums.add(nums.remove(0)); // rotate left: [1, 2, 3, 4] becomes [2, 3, 4, 1]
nums.add(0, nums.remove(nums.size() - 1)); // rotate right: [1, 2, 3, 4] becomes [4, 1, 2, 3]
Moving elements to another list
// a holds [5, 12, 7, 20]; b is empty; limit is 6
for (int i = a.size() - 1; i >= 0; i--) {
if (a.get(i) > limit) {
b.add(0, a.remove(i));
}
}
// a is [5]; b is [12, 7, 20]
Walking backward makes each removal safe, and adding each moved element at the front of b undoes the backward order, so b keeps the original order.
Moving every 0 to the end
// nums holds [0, 5, 0, 3]
int n = nums.size();
int i = 0;
for (int k = 0; k < n; k++) {
if (nums.get(i) == 0) {
nums.add(nums.remove(i)); // the next element slides into i
} else {
i++;
}
}
// nums is [5, 3, 0, 0]
The counter k guarantees exactly n passes, one per original element, while i points at the next element still to be examined. Each moved 0 goes to the end, beyond anything left to examine.
Apply It 🎯
Trace It ✍️
// nums holds [1, 2, 3, 4, 5]
nums.add(nums.remove(0));
nums.add(nums.remove(0));
nums.add(0, nums.remove(nums.size() - 1));
-
What is nums.get(0) after the segment runs?
-
What is nums.get(4) after the segment runs?
Part 4: Building New Lists and Combining Lists
📋 ArrayList Algorithms
Part 4 of 7 — Building New Lists and Combining Lists
Many list algorithms leave their input alone and return a new list. Part 1 built one, a filtered list of even numbers. This part covers the other ways to build a result list (CED Topic 4.10) and the algorithms that work across two lists at once.
| Pattern | What goes into the new list |
|---|---|
| Transform | one computed value per element, such as each word's length |
| Reverse | the same elements, in the opposite order |
| Parallel lists | elements of one list, chosen by values at the same index in another |
| Interleave | elements taken from two lists in turn |
| Common elements | elements of one list that also appear in another |
🔑 Key Concept: A method that returns a new list must create it with
newexactly once, before the loop, and return it after the loop. A method that modifies its parameter changes the caller's list and usually returns nothing. Read the prompt to see which one is asked for.
Transform: One Result per Element
public static ArrayList<Integer> lengths(ArrayList<String> words) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (String w : words) {
result.add(w.length()); // the int is autoboxed
}
return result;
}
lengths of [sun, cloud, rain] is [3, 5, 4]. The new list's element type can differ from the input's: Strings go in, Integers come out.
Reverse Into a New List
public static ArrayList<String> reversed(ArrayList<String> list) {
ArrayList<String> result = new ArrayList<String>();
for (String s : list) {
result.add(0, s); // each element goes in front of the ones before it
}
return result;
}
| s | result afterward |
|---|---|
| "a" | [a] |
| "b" | [b, a] |
| "c" | [c, b, a] |
A backward indexed loop with result.add(list.get(i)) gives the same list.
New List or Same List?
| The method... | The caller's list afterward | Returned |
|---|---|---|
builds result with new and adds to it | unchanged | the new list |
calls set, add or remove on its parameter | changed | often nothing |
executes return list; on its parameter | possibly changed | the same list: an alias, not a copy |
Returning the parameter itself does not make a copy. If the caller then changes the returned list, the original list changes too, because they are one object.
Concept Check 🎯
Segment A
public static ArrayList<Integer> doubled(ArrayList<Integer> nums) {
for (int i = 0; i < nums.size(); i++) {
nums.set(i, nums.get(i) * 2);
}
return nums;
}
ArrayList<Integer> orig = new ArrayList<Integer>();
orig.add(1);
orig.add(4);
ArrayList<Integer> d = doubled(orig);
d.add(9);
System.out.println(orig);
Parallel Lists
Two lists are parallel when the elements at the same index belong together, such as names.get(i) and scores.get(i).
public static ArrayList<String> passing(ArrayList<String> names,
ArrayList<Integer> scores, int cut) {
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < names.size(); i++) {
if (scores.get(i) >= cut) {
result.add(names.get(i));
}
}
return result;
}
For names [Ana, Ben, Cy] with scores [82, 64, 90] and cut 70, the result is [Ana, Cy]. The loop needs an index, because the same i must reach both lists. If code ever removes from one parallel list, it must remove at the same index from the other, or every later pair is mismatched.
Interleave
public static ArrayList<String> interleave(ArrayList<String> a, ArrayList<String> b) {
ArrayList<String> result = new ArrayList<String>();
int i = 0;
while (i < a.size() || i < b.size()) {
if (i < a.size()) {
result.add(a.get(i));
}
if (i < b.size()) {
result.add(b.get(i));
}
i++;
}
return result;
}
For a = [A, B, C] and b = [x, y], the result is [A, x, B, y, C]. The loop continues while either list has elements left (||), and each get is guarded by its own size test.
Common Elements
public static ArrayList<String> common(ArrayList<String> a, ArrayList<String> b) {
ArrayList<String> result = new ArrayList<String>();
for (String s : a) {
boolean inB = false;
for (String t : b) {
if (t.equals(s)) {
inB = true;
}
}
if (inB) {
result.add(s);
}
}
return result;
}
For a = [fig, kiwi, lime] and b = [lime, fig], the result is [fig, lime], in the order of a. The inner loop is the hand-written search that replaces a membership method, and the flag is reset to false for each new s.
Combining Lists 🔍
Apply It 🎯
Part 5: Data Analysis With ArrayList
📋 ArrayList Algorithms
Part 5 of 7 — Data Analysis With ArrayList
The free-response question on Data Analysis with ArrayList gives you a class that keeps a private ArrayList of objects, plus the class those objects come from. You write methods that traverse the list with getters to answer questions about the data, and sometimes to change it. This part works through one such class from start to finish and connects it to the data-set ideas in CED Topic 4.2.
| A typical method asks you to... | Algorithm from this lesson |
|---|---|
| total or average a value for some of the objects | accumulate with a condition (Part 2) |
| find the object with the largest or smallest value | maximum or minimum (Parts 1 and 2) |
| remove the objects that meet a condition | backward removal (Part 1) |
| compare each record with the one before it | neighbors (Part 2) |
| return a new list built from the data | build a new list (Part 4) |
The Classes
public class Reading {
private String station;
private int day;
private int rain; // millimeters of rain that day
public Reading(String s, int d, int r) {
station = s;
day = d;
rain = r;
}
public String getStation() { return station; }
public int getDay() { return day; }
public int getRain() { return rain; }
}
public class RainLog {
private ArrayList<Reading> readings;
public RainLog() {
readings = new ArrayList<Reading>();
}
public void addReading(Reading r) {
readings.add(r);
}
// methods written below
}
The examples in this part use a RainLog holding six readings, added in this order:
| Index | Station | Day | Rain (mm) |
|---|---|---|---|
| 0 | North | 1 | 12 |
| 1 | South | 1 | 0 |
| 2 | North | 2 | 30 |
| 3 | South | 2 | 5 |
| 4 | North | 3 | 0 |
| 5 | South | 3 | 18 |
Code inside RainLog cannot read r.rain directly, because rain is private to Reading. Every value comes through a getter, such as readings.get(i).getRain().
Totals and Averages for One Station
public int totalFor(String station) {
int total = 0;
for (Reading r : readings) {
if (r.getStation().equals(station)) {
total += r.getRain();
}
}
return total;
}
public double averageFor(String station) {
int total = 0;
int count = 0;
for (Reading r : readings) {
if (r.getStation().equals(station)) {
total += r.getRain();
count++;
}
}
if (count == 0) {
return 0.0;
}
return (double) total / count;
}
totalFor("North") is 12 + 30 + 0 = 42, and averageFor("North") is 42 / 3 = 14.0. The average counts only the matching readings, not readings.size().
The Wettest Reading
public Reading wettest() {
Reading best = readings.get(0);
for (Reading r : readings) {
if (r.getRain() > best.getRain()) {
best = r;
}
}
return best;
}
The method keeps a reference to the best object so far, not just its rain amount, so the caller can ask the returned Reading for its station and day. For the six readings it returns the North reading for day 2. The method assumes the list is not empty.
Concept Check 🎯
Removing Records
// Removes every reading from station and returns how many were removed
public int removeStation(String station) {
int removed = 0;
for (int i = readings.size() - 1; i >= 0; i--) {
if (readings.get(i).getStation().equals(station)) {
readings.remove(i);
removed++;
}
}
return removed;
}
The prompt says the method removes readings, so it must change the field readings itself. Building a new list of the readings to keep is acceptable only if the method then assigns that list to the field.
Comparing Each Record With the One Before
// Returns the largest increase in rain from one reading to the next,
// or 0 if the rain never increases
public int biggestJump() {
int best = 0;
for (int i = 1; i < readings.size(); i++) {
int jump = readings.get(i).getRain() - readings.get(i - 1).getRain();
if (jump > best) {
best = jump;
}
}
return best;
}
| i | Readings compared | jump | best afterward |
|---|---|---|---|
| 1 | 12 to 0 | -12 | 0 |
| 2 | 0 to 30 | 30 | 30 |
| 3 | 30 to 5 | -25 | 30 |
| 4 | 5 to 0 | -5 | 30 |
| 5 | 0 to 18 | 18 | 30 |
Here starting best at 0 is correct, because the specification says to return 0 when the rain never increases. Read the prompt: a plain "largest value" search would start from the first element instead.
Thinking About the Data
| Question | Can these readings answer it? |
|---|---|
| Which station had more total rain over the three days? | yes: compare totalFor for each station |
| How much rain fell at North at noon on day 2? | no: each reading is a daily total |
| Why was day 2 wetter at North? | no: the data records amounts, not causes |
Real data also needs cleaning. If a failed sensor records -1, a total that adds it is wrong; adding && r.getRain() >= 0 to the condition skips the invalid readings.
Why the Code Looks That Way 🔍
Mistakes in Data Analysis Answers
| Mistake | What goes wrong |
|---|---|
r.getStation() == station | compares references, so readings with matching text can be missed |
r.rain inside RainLog | does not compile: rain is private to Reading |
best = 0 when the values could all be negative | returns 0, a value that is not in the data |
| removing in a forward loop with no index adjustment | skips the reading after each removal |
| removing inside an enhanced for loop | can throw a ConcurrentModificationException |
total / count with two ints | drops the fraction of the average |
| building a new list but never storing it in the field | the field readings is unchanged |
📝 AP Connection: On this free-response question, use the getters given in the problem, keep to the six ArrayList methods on the Quick Reference, and make sure that a method that is supposed to change the list changes the field.
Apply It 🎯
Part 6: AP-Style Practice
📋 ArrayList Algorithms
Part 6 of 7 — AP-Style Practice
This part practices list algorithms the way the exam presents them: multiple-choice traces, then a full free-response question in the style of Data Analysis with ArrayList. Use only the Java Quick Reference subset.
How to Attack a List Algorithm
| Step | Do this |
|---|---|
| 1 | Find the loop's direction and whether the body changes the size. |
| 2 | After every add or remove, rewrite the list and decide which element the next pass will see. |
| 3 | For a result list, find where it is created: once before the loop, or wrongly inside it. |
| 4 | For objects, track references: remove(i) and get(i) both hand back the object itself. |
| 5 | Check the return: inside the loop (an early answer) or after it (the default answer). |
Practice Set 1: Tracing 🎯
Segment A (list holds [3, 6, 2, 8, 5])
for (int i = list.size() - 1; i > 0; i--) {
if (list.get(i) > list.get(i - 1)) {
list.remove(i - 1);
}
}
Segment B (w holds [go, stop, go, slow, go])
int pos = -1;
int count = 0;
for (int i = 0; i < w.size(); i++) {
if (w.get(i).equals("go")) {
count++;
pos = i;
}
}
System.out.println(count + " " + pos);
Segment C (a holds [1, 2, 3])
ArrayList<Integer> b = new ArrayList<Integer>();
for (int x : a) {
b.add(0, x * x);
}
a.set(0, b.get(0));
System.out.println(a + " " + b);
FRQ-Style Question — StudyLog
public class Session {
private String subject;
private int minutes;
public Session(String s, int m) {
subject = s;
minutes = m;
}
public String getSubject() { return subject; }
public int getMinutes() { return minutes; }
}
public class StudyLog {
private ArrayList<Session> sessions;
// constructor and other methods not shown
/** Returns the total minutes of all sessions for subject */
public int minutesFor(String subject)
{ /* part (a) */ }
/** Removes every session shorter than min minutes and returns a list of
the subjects of the removed sessions, in their original order */
public ArrayList<String> removeShort(int min)
{ /* part (b) */ }
}
Example. sessions holds (math, 30), (bio, 10), (math, 5), (art, 45), (bio, 20).
| Call | Returns | sessions afterward |
|---|---|---|
minutesFor("math") | 35 | unchanged |
minutesFor("chem") | 0 | unchanged |
removeShort(15) | [bio, math] | (math, 30), (art, 45), (bio, 20) |
Part (a) Solution
public int minutesFor(String subject) {
int total = 0;
for (Session s : sessions) {
if (s.getSubject().equals(subject)) {
total += s.getMinutes();
}
}
return total;
}
Part (b) Solution
public ArrayList<String> removeShort(int min) {
ArrayList<String> removed = new ArrayList<String>();
for (int i = sessions.size() - 1; i >= 0; i--) {
if (sessions.get(i).getMinutes() < min) {
removed.add(0, sessions.remove(i).getSubject());
}
}
return removed;
}
- The backward loop makes each removal safe.
sessions.remove(i)returns the Session it removed, so.getSubject()can be called on it in the same statement.- Visiting the list backward finds the short sessions in reverse order, and
add(0, ...)puts each subject in front of the ones found after it, restoring the original order.
What a Rubric Looks For
| Part | Point | Earned by |
|---|---|---|
| (a) | Traversal | visits every session with no out-of-bounds access |
| (a) | Comparison | compares subjects with equals, using the getter |
| (a) | Result | adds the minutes of matching sessions only, and returns the total after the loop |
| (b) | Removal | removes every session shorter than min without skipping any |
| (b) | Result list | creates one list before the loop and adds the removed subjects in their original order |
| (b) | Return | returns the list of subjects |
Practice Set 2: Reasoning About StudyLog 🎯
Trace the Example ✍️
The example StudyLog runs removeShort(15) and then minutesFor("bio").
-
How many subjects are in the list that removeShort(15) returns?
-
What does minutesFor("bio") return afterward?
Mistakes That Cost Points on This Question
| Mistake | Why it fails |
|---|---|
sessions[i] or sessions.length | array syntax on a list does not compile |
sessions.get(i).minutes | minutes is private to Session: use getMinutes() |
| a forward removal loop with no adjustment | skips the session after each removal |
creating removed inside the loop | a new empty list replaces it on every pass |
return inside the loop of part (a) | returns after the first matching session |
removing inside for (Session s : sessions) | can throw a ConcurrentModificationException |
| returning the subjects in reverse order | the prompt asks for their original order |
📝 AP Connection: Write each part so it works on its own. Part (b) may call part (a) or other methods in the class when that helps, and you may assume they work as specified.
Part 7: Synthesis Review
📋 ArrayList Algorithms
Part 7 of 7 — Synthesis Review
This part ties the ArrayList algorithms together (CED Topic 4.10). Use the table as a checklist, then test yourself on mixed questions.
The Topic on One Page
| Idea | Key fact | Typical trap |
|---|---|---|
| Removing while traversing (Part 1) | go backward, or do not advance after a removal | skipping the element that slides into i |
| Searching (Part 2) | no search method on the Quick Reference: write the loop | returning -1 inside the loop |
| Any / all (Part 2) | early return for the deciding case, default after the loop | an else branch that returns on the first pass |
| Min and max (Part 2) | keep an index or an object, start from the first element | starting at 0 for values that may be negative |
| Inserting (Part 3) | skip past an inserted element | a loop that keeps landing on what it inserted |
| Moving (Part 3) | remove returns the element it removed | losing the order when moving backward |
| New lists (Part 4) | create once before the loop, return after it | returning the parameter and calling it a copy |
| Two lists (Part 4) | one index for parallel lists; guard each get | && when the loop should run while either list has elements |
| Data analysis (Part 5) | getters, equals, and changes made to the field | == on Strings, private fields, int averages |
Worked Example: Putting It Together
ArrayList<Integer> nums = new ArrayList<Integer>();
int[] raw = {4, 9, 4, 1};
for (int r : raw) {
insertSorted(nums, r); // from Part 3
}
int i = 1;
while (i < nums.size()) {
int here = nums.get(i);
int before = nums.get(i - 1);
if (here == before) {
nums.remove(i);
} else {
i++;
}
}
nums.add(nums.remove(0));
System.out.println(nums + " " + countIncreases(nums)); // countIncreases from Part 2
| Step | What happens | nums afterward |
|---|---|---|
| insert 4, 9, 4, 1 | each value goes in sorted position; the second 4 goes before the first | [1, 4, 4, 9] |
| remove repeats | the second 4 equals the one before it and is removed | [1, 4, 9] |
| rotate left | remove(0) returns 1, and add appends it | [4, 9, 1] |
| countIncreases | 4 to 9 is an increase; 9 to 1 is not | returns 1 |
Output
[4, 9, 1] 1
Unboxing each value into an int before comparing makes == compare values. Comparing nums.get(i) == nums.get(i - 1) directly would compare two Integer references instead.
Mixed Review 1 🎯
Choosing the Algorithm
| The task says... | Pattern | Loop |
|---|---|---|
| "return the number of..." | count | enhanced for, counter returned after the loop |
| "return the index of the first..." | search | indexed forward, return i inside, -1 after |
| "return true if any / all..." | any / all | early return inside, the default after |
| "remove all..." | removal | indexed backward, or a while loop that advances only when nothing is removed |
| "insert ... in order" | sorted insert | while loop to find the place, then add(i, value) |
| "return a new list of..." | build | create the list before the loop, add, return after |
| "for each pair of neighbors..." | neighbors | indexed from 1, using get(i - 1) and get(i) |
| "for the elements at the same index in two lists..." | parallel | one index, stopping at the end of the shorter list |
Quick Fire 🔍
Mixed Review 2 🎯