AP Computer Science a Quiz: Implementing Arraylist Algorithms
20 questions · exam conditions
0:00
Implementing Arraylist AlgorithmsQuestion 1 of 20

public class ListFilter { public static ArrayList filterByLength(ArrayList words, int len) { ArrayList result = new ArrayList(); for (String word : words) { if (word.length() == len) { result.add(word); } } return result; } }

An ArrayList wordList contains ["the", "quick", "brown", "fox", "jumps"]. What are the contents of the ArrayList returned by the call ListFilter.filterByLength(wordList, 5)?

["the", "fox"]
[]
["quick", "brown", "jumps"]
["the", "quick", "brown", "fox", "jumps"]
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Implementing Arraylist Algorithms

Practice Implementing Arraylist Algorithms in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Implementing Arraylist Algorithms, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

public class ListFilter { public static ArrayList filterByLength(ArrayList words, int len) { ArrayList result = new ArrayList(); for (String word : words) { if (word.length() == len) { result.add(word); } } return result; } }

An ArrayList wordList contains ["the", "quick", "brown", "fox", "jumps"]. What are the contents of the ArrayList returned by the call ListFilter.filterByLength(wordList, 5)?

  1. ["the", "fox"]
  2. []
  3. ["quick", "brown", "jumps"] (correct answer)
  4. ["the", "quick", "brown", "fox", "jumps"]

Explanation: The method creates a new ArrayList and adds only those strings from the input list that have a length equal to the parameter len. In this case, len is 5. The words "quick", "brown", and "jumps" each have a length of 5 and are added to the result list, which is then returned.

Question 2

public class Checker { public static boolean hasDuplicates(ArrayList items) { for (int i = 0; i < items.size(); i++) { for (int j = i + 1; j < items.size(); j++) { if (items.get(i).equals(items.get(j))) { return true; } } } return false; } }

Which of the following ArrayLists would cause the method hasDuplicates to return true?

I. ["a", "b", "c", "d"]

II. ["a", "b", "c", "a"]

III. ["a", "a", "b", "c"]

  1. II only
  2. III only
  3. II and III only (correct answer)
  4. I, II, and III

Explanation: The method returns true if any element appears more than once. List I has no duplicates and will return false. List II has a duplicate "a" at the beginning and end, so it will return true. List III has a duplicate "a" at the first two positions, so it will return true. Therefore, both II and III will cause the method to return true.

Question 3

public class ListComparer { public static ArrayList findIntersection(ArrayList list1, ArrayList list2) { ArrayList common = new ArrayList(); for (Integer num1 : list1) { for (Integer num2 : list2) { if (num1.equals(num2)) { common.add(num1); } } } return common; } }

listA contains [10, 20, 30] and listB contains [20, 40, 30]. What are the contents of the ArrayList returned by the call ListComparer.findIntersection(listA, listB)?

  1. [30, 20]
  2. [20, 30] (correct answer)
  3. [10, 20, 30, 20, 40, 30]
  4. [10, 40]

Explanation: The method iterates through each element of list1 and compares it to every element in list2. If a match is found, the element from list1 is added to the common list. The first match found is 20, which is added. The second match found is 30, which is added. The final returned list is [20, 30]. The order is determined by the outer loop's traversal of list1.

Question 4

public class ListCleaner { public static void removeLongWords(ArrayList list) { for (int i = 0; i < list.size(); i++) { if (list.get(i).length() > 4) { list.remove(i); } } } }

An ArrayList of String objects named words is initialized with ["cat", "mouse", "snake", "elephant", "dog"]. What are the contents of words after the call ListCleaner.removeLongWords(words)?

  1. ["cat", "mouse", "dog"]
  2. ["cat", "snake", "dog"] (correct answer)
  3. ["cat", "dog"]
  4. An IndexOutOfBoundsException occurs.

Explanation: This method has a common bug. When an element is removed from an ArrayList while traversing with a standard forward for-loop, the subsequent element shifts to the current index, but the loop counter i still increments, causing that shifted element to be skipped. mouse (length 5) is removed, and snake shifts into its index. The loop increments i, skipping snake. Then elephant (length 8) is removed. The final list is ["cat", "snake", "dog"].

Question 5

public class Rotator { /** Precondition: list.size() > 0 */ public static void rotateRight(ArrayList list) { Integer last = list.remove(list.size() - 1); list.add(0, last); } }

An ArrayList named data contains [10, 20, 30, 40, 50]. What are the contents of data after the call Rotator.rotateRight(data)?

  1. [20, 30, 40, 50, 10]
  2. [10, 20, 30, 40]
  3. [50, 10, 20, 30, 40] (correct answer)
  4. [50, 20, 30, 40, 10]

Explanation: The method performs a right rotation. The last element (50) is removed from the end of the list, which becomes [10, 20, 30, 40]. Then, the removed element (50) is inserted at index 0. The final state of the list is [50, 10, 20, 30, 40].

Question 6

/** Precondition: The list contains Integer objects, including some nulls.

  • Postcondition: All non-null elements are moved to the beginning of
  •             the list, preserving their relative order. The list size
    
  •             remains unchanged, with nulls at the end. */
    

public class ListPacker { public static void pack(ArrayList list) { int insertPos = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i) != null) { list.set(insertPos, list.get(i)); insertPos++; } } for (int i = insertPos; i < list.size(); i++) { list.set(i, null); } } }

An ArrayList named data contains [null, 10, 20, null, 30]. What are the contents of data after the call ListPacker.pack(data)?

  1. [10, 20, 30]
  2. [10, 20, null, 30, null]
  3. [null, null, 10, 20, 30]
  4. [10, 20, 30, null, null] (correct answer)

Explanation: The first loop iterates through the list. When it finds a non-null element, it places it at the current insertPos and increments insertPos. After this loop, the list will be [10, 20, 30, null, 30], and insertPos will be 3. The second loop then iterates from insertPos to the end of the list, setting all those elements to null. This overwrites the remaining original elements, resulting in [10, 20, 30, null, null].

Question 7

public class ListUtil { /** Precondition: nums contains Integer objects. */ public static int sumPositive(ArrayList nums) { int total = 0; for (Integer num : nums) { if (num > 0) { total += num; } } return total; } }

An ArrayList of Integer objects named list is initialized with the values [10, -5, 3, -8, 2]. What is returned by the call ListUtil.sumPositive(list)?

  1. 2
  2. 10
  3. 15 (correct answer)
  4. 28

Explanation: The sumPositive method iterates through the ArrayList and adds only the positive values to total. In the given list, the positive values are 10, 3, and 2. The sum is 10 + 3 + 2 = 15.

Question 8

public class StringProcessor { /** Precondition: words is not null and words.size() > 0. */ public static String findShortest(ArrayList words) { String shortest = words.get(0); for (int i = 1; i < words.size(); i++) { if (words.get(i).length() < shortest.length()) { shortest = words.get(i); } } return shortest; } }

An ArrayList named wordList is initialized with the values ["apple", "banana", "kiwi", "fig", "grape"]. What is returned by the call StringProcessor.findShortest(wordList)?

  1. "apple"
  2. "fig" (correct answer)
  3. "kiwi"
  4. "grape"

Explanation: The method iterates through the list to find the string with the minimum length. The lengths are: "apple" (5), "banana" (6), "kiwi" (4), "fig" (3), "grape" (5). The string with the shortest length is "fig".

Question 9

public class Verifier { public static boolean allStartWith(ArrayList words, String prefix) { for (String word : words) { if (word.indexOf(prefix) != 0) { return false; } } return true; } }

An ArrayList of String objects named items contains ["prepaid", "prevent", "prefix", "prepare"]. Which of the following calls returns false?

  1. Verifier.allStartWith(items, "p")
  2. Verifier.allStartWith(items, "pre")
  3. Verifier.allStartWith(items, "prepa") (correct answer)
  4. Verifier.allStartWith(items, "")

Explanation: The method checks if all strings in the list start with the given prefix. The call with "prepa" will return false because the first string, "prepaid", does not start with "prepa". The method's condition word.indexOf("prepa") != 0 will be true, causing an immediate return of false. The other calls will return true as all words start with those prefixes.

Question 10

public class ListModifier { public static void process(ArrayList nums) { int i = 0; while (i < nums.size()) { if (nums.get(i) < 0) { nums.add(i, 0); } i++; } } }

What is the result when the process method is called with an ArrayList containing [10, -20, 30]?

  1. The list becomes [10, 0, -20, 30].
  2. The list becomes [10, 0, -20, 0, 30].
  3. The method enters an infinite loop. (correct answer)
  4. An IndexOutOfBoundsException occurs.

Explanation: When i is 1, nums.get(1) is -20. A 0 is inserted at index 1, shifting -20 to index 2. The list becomes [10, 0, -20, 30]. Then i increments to 2. At i=2, nums.get(2) is -20. Another 0 is inserted at index 2. The list becomes [10, 0, 0, -20, 30]. i increments to 3. The element -20 is always at index i, so a 0 is inserted before it in every iteration. Since nums.size() grows at the same rate as i, the condition i < nums.size() is always met, resulting in an infinite loop.

Question 11

public class Reverser { public static void reverseList(ArrayList list) { for (int i = 0; i < list.size() / 2; i++) { Integer temp = list.get(i); list.set(i, list.get(list.size() - 1 - i)); list.set(list.size() - 1 - i, temp); } } }

An ArrayList named numbers contains [1, 2, 3, 4, 5]. What are the contents of numbers after the call Reverser.reverseList(numbers)?

  1. [5, 4, 3, 2, 1] (correct answer)
  2. [1, 2, 3, 4, 5]
  3. [5, 4, 3, 4, 5]
  4. [1, 2, 3, 2, 1]

Explanation: The method implements an in-place reversal algorithm. It iterates through the first half of the list, swapping each element with its corresponding element from the end of the list. It swaps index 0 with 4, and index 1 with 3. The middle element at index 2 is not moved. The result is the list in reverse order: [5, 4, 3, 2, 1].

Question 12

public class PairCounter { public static int countIncreasingPairs(ArrayList nums) { int count = 0; for (int i = 0; i < nums.size() - 1; i++) { if (nums.get(i) < nums.get(i + 1)) { count++; } } return count; } }

An ArrayList named data contains [10, 20, 15, 25, 20]. What is returned by PairCounter.countIncreasingPairs(data)?

  1. 1
  2. 2 (correct answer)
  3. 3
  4. 4

Explanation: The method counts the number of adjacent pairs where the first element is less than the second. The pairs are (10, 20), (20, 15), (15, 25), and (25, 20). The increasing pairs are (10, 20) and (15, 25). Therefore, the method returns a count of 2.

Question 13

public class MysteryMover { public static void mystery(ArrayList data, String target) { int count = 0; for (int i = 0; i < data.size(); i++) { if (data.get(i).equals(target)) { count++; } else { data.set(i - count, data.get(i)); } } for (int i = 0; i < count; i++) { data.remove(data.size() - 1); } } }

Which of the following best describes what the mystery method does to the ArrayList data?

  1. It removes all occurrences of target from data, preserving the relative order of other elements. (correct answer)
  2. It moves all occurrences of target to the end of data, preserving relative order of other elements.
  3. It replaces all occurrences of target with the last element of data, then shortens the list.
  4. It removes all elements that are not equal to target from data, preserving their relative order.

Explanation: This method implements an efficient, single-pass removal algorithm. It iterates through the list, shifting non-target elements to the left to overwrite target elements. A counter keeps track of how many target elements have been seen. After the first loop, all non-target elements are at the beginning of the list, followed by leftover elements. The second loop removes the correct number of elements from the end of the list to complete the removal of all target strings.

Question 14

// This method is intended to remove all strings of length 3 from list. public class WordFilter { public static void removeShortWords(ArrayList list) { for (int i = 0; i < list.size(); i++) { if (list.get(i).length() == 3) { list.remove(i); } } } }

The removeShortWords method does not work as intended because it can skip elements. For example, if list is ["one", "two", "ten", "four"], the method incorrectly leaves ["two", "four"]. Which of the following changes will correct the method?

  1. Traverse the list backwards, from list.size() - 1 down to 0.
  2. After removing an element at index i, decrement i by one.
  3. Use an enhanced for-loop, which automatically handles size changes.
  4. Both A and B would correct the method. (correct answer)

Explanation: The error occurs because removing an element at index i shifts the next element into index i, but the loop proceeds to i+1, skipping the shifted element. Traversing backwards (A) avoids this, as removing an element does not affect elements at earlier indices that are yet to be visited. Decrementing i after a removal (B) also fixes the bug by ensuring the loop re-evaluates the element that just shifted into the current index. An enhanced for-loop (C) would throw a ConcurrentModificationException and is incorrect. Since both A and B are valid corrections, D is the best choice.

Question 15

// Assume the Person class has a constructor and these methods: // public String getName() // public int getAge() public class RosterUtil { public static String findOldest(ArrayList people) { if (people.size() == 0) { return "None"; } Person oldestPerson = people.get(0); for (int i = 1; i < people.size(); i++) { Person currentPerson = people.get(i); if (currentPerson.getAge() > oldestPerson.getAge()) { oldestPerson = currentPerson; } } return oldestPerson.getName(); } }

An ArrayList of Person objects named roster contains three objects with the following attributes: (Name: "Ann", Age: 25), (Name: "Ben", Age: 30), (Name: "Cora", Age: 25). What is returned by the call RosterUtil.findOldest(roster)?

  1. "Ann"
  2. "Ben" (correct answer)
  3. "Cora"
  4. "None"

Explanation: The method implements a standard algorithm to find the maximum value. It iterates through the ArrayList, keeping track of the Person object with the highest age found so far. In the given list, Ben has the maximum age of 30. The method returns the name of this Person object, which is "Ben".

Question 16

// This method is intended to move the first element of a list to the end. /** Precondition: list.size() > 0 / public class ListShuffler { public static void moveFirstToEnd(ArrayList list) { / missing code */ } }

Which of the following code segments can replace /* missing code */ so the method works as intended?

  1. String first = list.get(0); list.add(first);
  2. String first = list.remove(0); list.add(first);
  3. list.add(list.remove(0));
  4. Both B and C would work as intended. (correct answer)

Explanation: The goal is to remove the first element and add it to the end. Option B correctly removes the element at index 0, stores it in a variable, and then adds that variable to the end of the list. Option C achieves the same result more concisely by passing the return value of list.remove(0) directly to the list.add() method. Option A is incorrect because get(0) does not remove the element, resulting in a duplicate. Since both B and C are correct, D is the best answer.

Question 17

/** Returns the index of the first occurrence of target in list,

  • or -1 if target is not found. / public class Finder { public static int findFirst(ArrayList list, String target) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(target)) { / missing code */ } } return -1; } }

Which of the following can replace /* missing code */ so that the method works as intended?

  1. return i; (correct answer)
  2. break;
  3. return list.get(i);
  4. return list.indexOf(target);

Explanation: The method is designed to return the index of the first match. Inside the loop, when list.get(i) equals target, the current index i should be returned immediately. return i; accomplishes this. break; would exit the loop, but the method would then execute return -1;, which is incorrect. return list.get(i); returns a String, which is the wrong return type. indexOf is not available on ArrayList and is what the method is implementing.

Question 18

public class Swapper { // Precondition: 0 <= i < list.size(), 0 <= j < list.size() public static void swap(ArrayList list, int i, int j) { Integer temp = list.get(i); list.set(i, list.get(j)); list.set(j, temp); } }

An ArrayList named data contains [5, 10, 15, 20]. What are the contents of data after the call Swapper.swap(data, 1, 3)?

  1. [5, 10, 15, 20]
  2. [20, 10, 15, 5]
  3. [5, 20, 15, 10] (correct answer)
  4. [5, 15, 10, 20]

Explanation: The swap method exchanges the elements at the specified indices i and j. The call swap(data, 1, 3) will swap the element at index 1 (which is 10) with the element at index 3 (which is 20). The resulting list will be [5, 20, 15, 10].

Question 19

public class ListPruner { public static void removeEvenLength(ArrayList words) { int i = 0; while (i < words.size()) { if (words.get(i).length() % 2 == 0) { words.remove(i); } else { i++; } } } }

An ArrayList of String objects named list is initialized with ["a", "bb", "ccc", "dddd", "ee"]. What are the contents of list after the call ListPruner.removeEvenLength(list)?

  1. ["a", "ccc", "ee"]
  2. ["a", "ccc"] (correct answer)
  3. ["a", "bb", "ccc"]
  4. ["a", "dddd"]

Explanation: This method correctly removes elements from a list while traversing it in a forward direction. The index i is incremented only when an element is NOT removed. Tracing the execution: "bb" is removed, list becomes ["a", "ccc", "dddd", "ee"]; i is not incremented. Next, "ccc" is checked and kept, i increments. Then "dddd" is removed, list becomes ["a", "ccc", "ee"]; i is not incremented. Finally, "ee" is removed. The loop terminates, leaving ["a", "ccc"].

Question 20

public class GradeAnalyzer { public static double calculateAverage(ArrayList scores) { if (scores.size() == 0) { return 0.0; } double sum = 0; for (Integer score : scores) { sum += score; } return sum / scores.size(); } }

An ArrayList named testScores contains [80, 90, 100, 70]. What is returned by the call GradeAnalyzer.calculateAverage(testScores)?

  1. 85
  2. 340.0
  3. 85.25
  4. 85.0 (correct answer)

Explanation: The method calculates the sum of the scores, which is 80 + 90 + 100 + 70 = 340. It then divides the sum by the number of scores, which is 4. Because sum is a double, the division 340.0 / 4 results in the double value 85.0, which is returned.