AP® Computer Science A Data Collections Practice Questions
Work through AP Computer Science A practice questions on Data Collections, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: Arraylists Clear filter
Question 182
Question 183
Question 184
Question 185
What is printed?
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4); list.add(4); list.add(3);
list.add(4); list.add(4);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 4) {
list.remove(i);
}
}
System.out.println(list);Main Solution
To determine what is printed, trace through the code step by step.
Initial list: [4, 4, 3, 4, 4] (indices 0–4)
Loop iteration by iteration:
- i = 0:
list.get(0)is 4, solist.remove(0)is called. List becomes [4, 3, 4, 4].iincrements to 1. - i = 1:
list.get(1)is 3 (not 4), so nothing is removed.iincrements to 2. - i = 2:
list.get(2)is 4, solist.remove(2)is called. List becomes [4, 3, 4].iincrements to 3. - i = 3:
list.size()is now 3, so3 < 3is false. Loop ends.
Final list: [4, 3, 4]
System.out.println(list) prints [4, 3, 4], which matches option B.
The key insight is that when an element is removed at index i, all subsequent elements shift left by one position, but i still increments. This causes every other matching element to be skipped.
Teacher Explanation
This question tests students' understanding of the pitfall of removing elements from an ArrayList while iterating over it with an index-based for loop. When list.remove(i) is called, the element at index i is deleted and all elements after it shift left. Since i then increments, the element that shifted into position i is never checked. This causes alternating 4s to be skipped, leaving [4, 3, 4] in the list.
Education Coach Advice
When you see an ArrayList being modified inside a for loop, always trace through the loop manually, updating the list contents and indices after each removal. Remember: removing at index i shifts everything after it left by 1, so the next element effectively moves to index i — but the loop still increments i, causing a skip. This is a classic AP CSA trap.
Traps
Option A ([]) is tempting if students assume all 4s are removed, but the loop skips elements due to index shifting after each removal.
Option C ([3]) is similarly wrong — students might think all 4s are eventually removed, but the skipping behavior prevents that.
Option D ([4, 4]) might be chosen if students miscount which elements are skipped. The correct trace shows that the first and third 4s (at original indices 0 and 2) are removed, leaving the second 4 (original index 1 — but wait, that's a 3), the fourth 4 (original index 3), and the fifth 4 (original index 4) — but the loop exits before checking index 3 again after the second removal.
Answer images
Question 186
What is printed?
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) { list.add(i * i); }
for (int i = 0; i < list.size() - 1; i++) {
list.set(i, list.get(i) + list.get(i + 1));
}
System.out.println(list);Main Solution
Step 1: Build the initial list.
The first loop runs for i = 0, 1, 2, 3, 4 and adds i * i:
- i=0: 00 = 0
- i=1: 11 = 1
- i=2: 22 = 4
- i=3: 33 = 9
- i=4: 4*4 = 16
List after first loop: [0, 1, 4, 9, 16]
Step 2: Run the second loop.
The second loop runs while i < list.size() - 1, i.e., i < 4, so i = 0, 1, 2, 3. Each iteration sets list[i] = list[i] + list[i+1]. Crucially, each update is immediately visible to subsequent iterations because the list is modified in place.
- i=0: list[0] = list[0] + list[1] = 0 + 1 = 1 → list:
[1, 1, 4, 9, 16] - i=1: list[1] = list[1] + list[2] = 1 + 4 = 5 → list:
[1, 5, 4, 9, 16] - i=2: list[2] = list[2] + list[3] = 4 + 9 = 13 → list:
[1, 5, 13, 9, 16] - i=3: list[3] = list[3] + list[4] = 9 + 16 = 25 → list:
[1, 5, 13, 25, 16]
The last element (index 4) is never updated because the loop stops at i < 4. It remains 16.
Final output: [1, 5, 13, 25, 16], which is option D.
Teacher Explanation
This question tests understanding of in-place ArrayList mutation during iteration. The key insight is that each list.set(i, ...) immediately changes the value at index i, so subsequent iterations use the already-updated values — not the originals. Additionally, the loop condition i < list.size() - 1 means the last element (index 4) is never written to, so it stays at 16.
Education Coach Advice
When tracing ArrayList mutations in a loop, always update your mental model of the list after each iteration — don't assume the original values persist. Also, carefully check the loop's stopping condition: i < list.size() - 1 means the last index is excluded. On the AP exam, these boundary conditions are frequently tested.
Traps
Option A [1, 5, 13, 25, 25] is the most common trap. Students who correctly trace the first four updates but then assume the last element also gets updated (perhaps thinking the loop runs one more iteration, or that the last element becomes 25 by some other logic) will choose A. The loop condition i < list.size() - 1 (i.e., i < 4) stops at i=3, so index 4 is never touched and remains 16.
Option C [1, 4, 9, 16, 16] would result if students mistakenly used the original values for all additions (i.e., treated it as if a copy were used), but only for the first element being 1 — this is inconsistent reasoning.
Answer images
Question 187
An online community platform stores user posts as strings in an ArrayList. The moderation team needs tools to clean up duplicate content and identify trending topics. You are writing two analysis methods for the MessageBoard class.
PART A
Write the method public ArrayList<String> removeDuplicates(ArrayList<String> posts) that returns a new ArrayList containing only the first occurrence of each unique string, in original order.
For example, if posts is ["hello", "world", "hello", "java", "world", "hello"], the method returns ["hello", "world", "java"].
public ArrayList<String> removeDuplicates(ArrayList<String> posts) {PART B
Write the method public String mostFrequent(ArrayList<String> posts) that returns the string appearing most often. If there is a tie, return the one that appears first in the list.
For example, if posts is ["cat", "dog", "cat", "bird", "dog", "cat"], the method returns "cat" (appears 3 times).
public String mostFrequent(ArrayList<String> posts) {Main Solution
PART A — removeDuplicates
The goal is to iterate through posts and add each string to a new ArrayList only if it has not already been added. This preserves the first occurrence and maintains original order.
public ArrayList<String> removeDuplicates(ArrayList<String> posts) {
ArrayList<String> result = new ArrayList<String>();
for (String post : posts) {
if (!result.contains(post)) {
result.add(post);
}
}
return result;
}Trace with example: posts = ["hello", "world", "hello", "java", "world", "hello"]
- "hello" → not in result → add → result = ["hello"]
- "world" → not in result → add → result = ["hello", "world"]
- "hello" → already in result → skip
- "java" → not in result → add → result = ["hello", "world", "java"]
- "world" → already in result → skip
- "hello" → already in result → skip
Returns ["hello", "world", "java"] ✓
PART B — mostFrequent
The goal is to find the string with the highest frequency. In case of a tie, the one that appears first in the list wins. We iterate through each unique string (using the result of removeDuplicates or a manual check), count its occurrences, and track the maximum.
public String mostFrequent(ArrayList<String> posts) {
if (posts == null || posts.size() == 0) {
return null;
}
String mostFreq = posts.get(0);
int maxCount = 0;
// Count occurrences of each string in original order
ArrayList<String> seen = new ArrayList<String>();
for (String post : posts) {
if (!seen.contains(post)) {
seen.add(post);
int count = 0;
for (String s : posts) {
if (s.equals(post)) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mostFreq = post;
}
}
}
return mostFreq;
}Trace with example: posts = ["cat", "dog", "cat", "bird", "dog", "cat"]
- "cat": count = 3 → maxCount = 3, mostFreq = "cat"
- "dog": count = 2 → 2 < 3, no update
- "bird": count = 1 → 1 < 3, no update
Returns "cat" ✓
Tie-breaking note: Because we iterate through posts in order and only update mostFreq when count > maxCount (strict greater-than), the first string encountered with the highest count is retained, satisfying the tie-breaking requirement.
Teacher Explanation
Part A tests the student's ability to build a new collection by filtering duplicates using ArrayList.contains() and a for-each loop. Key scoring points: (1) creates and returns a new ArrayList, (2) uses contains or equivalent logic to check for prior occurrence, (3) adds only on first occurrence, (4) preserves original order.
Part B tests nested iteration to count frequencies and track a running maximum. Key scoring points: (1) correctly counts occurrences of each string, (2) uses strict > (not >=) to preserve first-occurrence tie-breaking, (3) returns the correct string, (4) handles the full list without skipping elements.
Education Coach Advice
AP Exam Strategy:
- For Part A, always create a new ArrayList and return it — never modify the parameter directly unless the prompt explicitly says to.
- For Part B, write out a small trace (like the example given) to verify your tie-breaking logic before finalizing your answer.
- Use
.equals()for all String comparisons in Java — never==. - Read the tie-breaking rule carefully: "first in the list" means use strict
>, not>=. - If you use a helper method (like calling
removeDuplicatesinsidemostFrequent), make sure it is correctly implemented — errors propagate.
Traps
Part A traps:
- Modifying the original
postslist instead of creating a new one — loses points for not returning a new ArrayList. - Using
==instead of.equals()for String comparison — will fail for non-interned strings. - Forgetting to return the result list.
Part B traps:
- Using
>=instead of>when updating the maximum — this would return the last string with the highest count instead of the first, violating the tie-breaking rule. - Counting each string multiple times (not tracking which strings have already been counted) — leads to redundant work but may still produce correct output; however, it risks off-by-one logic errors.
- Returning
nullor an empty string when the list is non-empty.
Question 188
What is printed?
ArrayList<String> words = new ArrayList<String>();
words.add("cat"); words.add("dog"); words.add("car");
words.add("dot"); words.add("cup");
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < words.size(); i++) {
String w = words.get(i);
if (w.substring(0, 1).equals("c")) {
result.add(w);
}
}
for (int i = result.size() - 1; i >= 0; i--) {
if (result.get(i).indexOf("a") != -1) {
result.remove(i);
}
}
System.out.println(result);Main Solution
Step 1: Build the words list.
words = ["cat", "dog", "car", "dot", "cup"]
Step 2: First loop — collect words starting with "c".
We iterate through words and check w.substring(0, 1).equals("c"):
- "cat" → starts with 'c' → added
- "dog" → starts with 'd' → skipped
- "car" → starts with 'c' → added
- "dot" → starts with 'd' → skipped
- "cup" → starts with 'c' → added
After first loop: result = ["cat", "car", "cup"]
Step 3: Second loop — iterate backwards and remove words containing "a".
We iterate from i = result.size() - 1 = 2 down to i = 0, removing any element where indexOf("a") != -1:
i = 2:result.get(2)= "cup" →"cup".indexOf("a")= -1 → NOT removedi = 1:result.get(1)= "car" →"car".indexOf("a")= 1 ≠ -1 → removed.result = ["cat", "cup"]i = 0:result.get(0)= "cat" →"cat".indexOf("a")= 1 ≠ -1 → removed.result = ["cup"]
Step 4: Print result.
System.out.println(result) prints the ArrayList's toString(), which is [cup].
The correct answer is D: [cup].
Teacher Explanation
This question tests two key skills: (1) iterating an ArrayList and filtering by string methods (substring, equals), and (2) safely removing elements from an ArrayList by iterating backwards. The backwards iteration avoids index-skipping issues. Words starting with 'c' are: "cat", "car", "cup". Then any of those containing 'a' ("cat" and "car") are removed, leaving only "cup".
Education Coach Advice
When tracing ArrayList removal loops, always simulate the index changes step by step. Backwards iteration is the safe pattern — it avoids skipping elements. For each iteration, write down the current state of the list and the current index. Also remember that indexOf returns -1 when the substring is NOT found, so != -1 means the substring IS present.
Traps
Option A [cat, car, cup]: A student might think the second loop does nothing, perhaps misreading the condition or thinking indexOf returns 0 for not found. Option B [cat, cup]: A student might think only "car" is removed (perhaps iterating forward and skipping "cat" after "car" is removed, which would actually skip "cup" — this trap is subtle). Option C [car, cup]: A student might think only "cat" is removed, perhaps confusing the condition or only checking the first character. The key insight is that BOTH "cat" and "car" contain the letter 'a', so both are removed, leaving only "cup".
Answer images
Question 189
What is printed?
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 6; i++) {
list.add(i * i);
}
// list = [1, 4, 9, 16, 25, 36]
for (int i = list.size() - 1; i >= 1; i -= 2) {
list.set(i, list.get(i) - list.get(i - 1));
}
System.out.println(list);Main Solution
The list is first populated with squares of 1 through 6:
list = [1, 4, 9, 16, 25, 36] (indices 0–5)
The second loop runs with i starting at list.size() - 1 = 5, decrementing by 2 each iteration, and stopping when i < 1. So i takes values: 5, 3, 1.
For each iteration, the operation is: list.set(i, list.get(i) - list.get(i - 1))
- i = 5: list.set(5, list.get(5) - list.get(4)) = list.set(5, 36 - 25) = list.set(5, 11)
list = [1, 4, 9, 16, 25, 11] - i = 3: list.set(3, list.get(3) - list.get(2)) = list.set(3, 16 - 9) = list.set(3, 7)
list = [1, 4, 9, 7, 25, 11] - i = 1: list.set(1, list.get(1) - list.get(0)) = list.set(1, 4 - 1) = list.set(1, 3)
list = [1, 3, 9, 7, 25, 11]
Final list: [1, 3, 9, 7, 25, 11], which matches option A.
Teacher Explanation
This question tests students' ability to trace through an ArrayList manipulation loop that iterates backwards with a step of -2, modifying only odd-indexed elements. The key insight is that the loop modifies indices 5, 3, and 1 (in that order), and each modification uses the already-updated list values — but since we go from high to low indices, the values at i-1 (even indices) are never modified and remain as the original squares.
Education Coach Advice
When tracing loops that modify a list in-place, always track the current state of the list after each iteration. Write out the list after each set() call. For loops that decrement by 2, carefully list all values of i before starting the trace: here 5 → 3 → 1 → (0 fails condition i >= 1, so stop). Don't forget the last iteration!
Traps
Option B [1, 4, 9, 7, 25, 11] is the most common trap: students may miss the final iteration where i = 1 and forget to update index 1 (changing 4 to 3). They correctly compute indices 5 and 3 but stop the loop trace early.
Option D [1, 3, 5, 7, 11, 11] is another trap for students who think the loop modifies all elements or uses cumulative differences incorrectly.
Answer images
Question 190
A neighborhood book club meets monthly to discuss and rate books. Members rate each book on a scale of 1 to 10, and the club maintains two parallel ArrayLists: one for book titles and one for their average ratings. The BookClub class provides methods to help members select their next read.
PART A
Write the method public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer> ratings, int threshold) that returns a new ArrayList containing only the titles whose corresponding rating is greater than or equal to threshold, preserving the original order.
For example, if titles is ["Dune", "1984", "Cosmos", "Beloved"] and ratings is [9, 7, 8, 6] with threshold 8, the method returns ["Dune", "Cosmos"].
public ArrayList<String> getTopRated(ArrayList<String> titles, ArrayList<Integer>
ratings, int threshold) {PART B
Write the method public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) that removes and returns the title with the highest rating. If there is a tie, remove and return the one appearing earliest in the list. Both the titles and ratings lists should have the corresponding element removed.
For example, if titles is ["Dune", "1984", "Cosmos"] and ratings is [9, 7, 9], the method returns "Dune" (first with highest rating 9) and both lists are reduced to ["1984", "Cosmos"] and [7, 9].
public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) {Main Solution
PART A — getTopRated
Algorithm: Create a new ArrayList<String>. Iterate through every index of titles. At each index, compare the corresponding element of ratings to threshold. If the rating is greater than or equal to threshold, add the title at that index to the result list. Return the result list.
public ArrayList<String> getTopRated(ArrayList<String> titles,
ArrayList<Integer> ratings, int threshold) {
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < titles.size(); i++) {
if (ratings.get(i) >= threshold) {
result.add(titles.get(i));
}
}
return result;
}Trace with example: titles = ["Dune", "1984", "Cosmos", "Beloved"], ratings = [9, 7, 8, 6], threshold = 8.
- i=0: rating 9 ≥ 8 → add "Dune"
- i=1: rating 7 ≥ 8? No
- i=2: rating 8 ≥ 8 → add "Cosmos"
- i=3: rating 6 ≥ 8? No
Returns ["Dune", "Cosmos"] ✓
PART B — recommend
Algorithm: Track the index of the maximum rating seen so far. Initialize maxIndex = 0. Iterate from index 1 through the end of ratings. If the current rating is strictly greater than the rating at maxIndex, update maxIndex. (Using strictly greater than ensures ties are broken by earliest occurrence.) After the loop, save the title at maxIndex, then remove the element at maxIndex from both titles and ratings. Return the saved title.
public String recommend(ArrayList<String> titles, ArrayList<Integer> ratings) {
int maxIndex = 0;
for (int i = 1; i < ratings.size(); i++) {
if (ratings.get(i) > ratings.get(maxIndex)) {
maxIndex = i;
}
}
String topTitle = titles.get(maxIndex);
titles.remove(maxIndex);
ratings.remove(maxIndex);
return topTitle;
}Trace with example: titles = ["Dune", "1984", "Cosmos"], ratings = [9, 7, 9].
- maxIndex starts at 0 (rating 9)
- i=1: rating 7 > 9? No
- i=2: rating 9 > 9? No (tie — maxIndex stays 0)
topTitle = "Dune". Remove index 0 from both lists → titles = ["1984", "Cosmos"], ratings = [7, 9]. Returns "Dune" ✓
Teacher Explanation
Part A tests the ability to traverse two parallel ArrayLists simultaneously using a standard index-based for loop and selectively populate a new list — a core AP CSA skill. Students must use >= (not >) for the threshold comparison and must not modify the original lists.
Part B tests finding the index of a maximum value in a list, then using that index to remove corresponding elements from two parallel lists. The key subtlety is using strictly greater than when updating maxIndex so that ties resolve to the earliest occurrence. Students must remove from both lists using the same index, and must save the title before removing it.
Education Coach Advice
AP Exam Strategy:
- For parallel-list problems, always use an index-based
forloop so you can access both lists at the same index simultaneously. - When building a filtered list, create the new
ArrayListat the top of the method and return it at the bottom — don't forget thereturnstatement. - For "find and remove the max" problems, find the index first, save what you need, then remove. Never remove inside the search loop.
- Trace your code with the given example before moving on — it takes 30 seconds and catches most off-by-one and operator errors.
- Remember:
ArrayList.remove(int index)removes by position; make sure you're not accidentally callingremove(Object).
Traps
Part A traps:
- Using
>instead of>=for the threshold check — would exclude books rated exactly at the threshold. - Modifying the original
titleslist instead of building a new one. - Using an enhanced for-each loop over
titleswithout tracking the index, making it impossible to look up the corresponding rating.
Part B traps:
- Using
>=instead of>when updatingmaxIndex— this would cause ties to resolve to the last occurrence rather than the first. - Forgetting to remove the element from one of the two lists.
- Removing from
titlesfirst and then trying to remove fromratingsat the same index — this is actually fine since both use the same savedmaxIndex, but students who re-calltitles.indexOf(...)after removal may get the wrong index. - Not saving the title string before calling
remove().
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

