AP Computer Science A • Unit 4.10

Implementing ArrayList Algorithms

Detailed answer explanations for the Unit 4.10 multiple-choice practice questions.

Q1A
Q2D
Q3B
Q4C
Q5C
Q6B
Q7D
Q8C
Q9A
Q10C
Q11A
Q12D
Q13B
Q14C
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

Which action is required by a count algorithm?

AIncrement a counter for each match
BReturn at the first match
CReplace every matching element
DUse the list size as the answer
Correct answer: A. A count algorithm keeps a counter and adds one to it every time an element has the property being checked.
Explanation

Sum, average, min, max, and count all combine a traversal with an accumulator: the loop visits the values and the accumulator keeps the result built so far. In countUrgent the accumulator is count, and the helper method isUrgent decides whether the current element deserves an increment.

  • B is not correct: Returning at the first match is the any pattern; it stops the traversal early, so no running total is ever built.
  • C is not correct: Counting is read-only work that records how many elements match; replacing elements changes the contents of the list instead.
  • D is not correct: size() reports how many elements are stored, not how many of them satisfy the condition being tested.
Q2

A method returns the average of an ArrayList<Integer>. Which expression avoids integer division?

Asum / list.size()
Bsum % list.size()
Clist.size() / sum
Dsum / (double) list.size()
Correct answer: D. Casting one operand to double is what the section's average method does, and it is what keeps the division from being an integer division.
Explanation

The average method returns sum(a) / (double) a.size(), so the total is divided by a double rather than by an int. The same method also guards the empty case first, returning 0.0 when a.size() == 0.

  • A is not correct: Both sum and list.size() are int values here, which is exactly the integer division the question asks you to avoid.
  • B is not correct: The remainder operator reports what is left over after dividing, so it does not produce the average of the stored values.
  • C is not correct: This divides the number of elements by the total, which reverses the two parts of an average and is still an int division.
Q3

Where does an any algorithm return false?

ABefore the loop
BAfter the loop finds no match
CAt the first match
DInside every iteration
Correct answer: B. An any check returns false only after the loop has visited every element and found no match.
Explanation

Return placement is what distinguishes these patterns. An any check returns true at the first match and false after the loop; an all check is the mirror image, returning false at the first failure and true after the loop.

  • A is not correct: Returning before the loop would answer the question without examining a single element of the list.
  • C is not correct: The first match is where an any check returns true, since one match is enough to settle the answer.
  • D is not correct: Returning inside every iteration would end the method on the first element, so the remaining elements would never be examined.
Q4

After inserting at index i, what happens to the element formerly at i?

AIt is deleted.
BIt stays at i.
CIt shifts to i + 1.
DIt moves to the end.
Correct answer: C. Insertion shifts later elements right, so the element formerly at index i ends up at index i + 1.
Explanation

The indexed add makes room at the requested position by moving that element and everything after it one position higher, and the list grows by one. The markGo method relies on this: after words.add(i + 1, "!") it writes an extra i++ so the loop skips the element just inserted.

  • A is not correct: Insertion adds an element rather than taking one out; it is deletion that removes a value and shifts later elements left.
  • B is not correct: If the old element stayed at index i, the inserted element would have no position of its own to occupy.
  • D is not correct: Each element from index i onward moves exactly one position right; none of them is relocated to the end of the list.
Q5

Consider the following method. What is returned for ["sun", "planet", "sky"]?

public static boolean allShort(ArrayList<String> a) {
    for (String s : a) {
        if (s.length() >= 6) {
            return false;
        }
    }
    return true;
}
Atrue, because one word is short
Btrue, because the loop finishes
Cfalse, because "planet" has length 6
DThe method does not compile.
Correct answer: C. "planet" has length 6, so the condition s.length() >= 6 is true and the method returns false at that element.
Explanation

This is an all check: it returns false at the first failure and true only after the loop has finished with no failure. One element that breaks the property is enough to end the traversal and settle the answer.

  • A is not correct: One short word does not decide an all check, because every element has to pass before the method can report true.
  • B is not correct: The loop does not finish here; the second element triggers the early return before the last word is examined.
  • D is not correct: The method traverses strings with an enhanced for loop and returns a boolean on both paths, so there is nothing to reject.
Q6

Assume names initially contains ["Iris", "Omar", "Zoe"]. What does names contain afterward?

names.add(0, names.remove(1));
A[Iris, Omar, Zoe]
B[Omar, Iris, Zoe]
C[Omar, Zoe]
D[Iris, Zoe, Omar]
Correct answer: B. remove(1) deletes and returns "Omar", and the indexed add then inserts that returned name at index 0.
Explanation

Java evaluates the inner method call first, so the element handed back by remove becomes the argument to add. Deletion shifts the later element left and the insertion shifts elements right again, so the size is unchanged and only the order differs.

  • A is not correct: The statement really does rearrange the list, since "Omar" is taken out of the middle and put back at the front.
  • C is not correct: The removed name is not lost, because the value returned by remove is immediately reused as the argument to add.
  • D is not correct: The insertion index is 0, so the returned name goes to the front of the list rather than to the end.
Q7

Assume trees initially contains ["oak", "pine"]. What does trees contain afterward?

trees.add(trees.set(0, "elm"));
A[oak, pine, elm]
B[elm, oak, pine]
C[elm, pine]
D[elm, pine, oak]
Correct answer: D. set(0, "elm") replaces the first element and returns "oak", which the one-argument add then appends.
Explanation

set returns the element it replaces, and the inner call is evaluated before add runs. The replacement happens at an existing index, so it does not change the size; the append afterward makes the list one element longer.

  • A is not correct: set writes "elm" into index 0, so "oak" cannot still be sitting at the front.
  • B is not correct: This add call has no index argument, so the returned element is appended at the end instead of inserted first.
  • C is not correct: The element returned by set is reused as the argument to add, so the list gains a third element rather than keeping two.
Q8

Assume a contains [2, 5] and b contains [7, 1]. What is the value of total?

int total = 0;
for (int i = 0; i < a.size(); i++) {
    total += a.get(i) * b.get(i);
}
A10
B15
C19
D70
Correct answer: C. Parallel traversal pairs index 0 with index 0 and index 1 with index 1, giving 2 times 7 plus 5 times 1.
Explanation

One indexed loop reads both lists, and matching indexes must represent related items. The accumulator total keeps the running result, adding each aligned product as the loop advances.

  • A is not correct: The accumulator adds 14 and then 5, so 10 matches neither the first product alone nor the finished total.
  • B is not correct: 15 is what adding all four stored elements would give, but the loop multiplies each aligned pair before adding.
  • D is not correct: 70 multiplies the two products by each other, while the loop adds each product into total instead.
Q9

Consider the following method. What is returned for [2, 5, 4, 7]?

public static int rises(ArrayList<Integer> a) {
    int count = 0;
    for (int i = 0; i < a.size() - 1; i++) {
        if (a.get(i) < a.get(i + 1)) {
            count++;
        }
    }
    return count;
}
A2
B3
C4
D18
Correct answer: A. Only the pairs 2 then 5 and 4 then 7 rise, so the counter ends at 2.
Explanation

This is a consecutive-pair count: each iteration compares indexes i and i + 1, so the last starting index is size() - 2. Being a count rather than an any check, it keeps going through every pair and increments only when the earlier value is smaller.

  • B is not correct: 3 would require counting 5 followed by 4 as well, but that pair falls rather than rises.
  • C is not correct: 4 is the number of elements, and a list of four elements offers only three consecutive pairs to examine.
  • D is not correct: 18 is the sum of the stored values, which is what an accumulator adding elements would build, not a count of pairs.
Q10

The following condition is used inside nested loops that compare indexes i and j in an ArrayList<String> named x. Which replacement correctly checks whether the two strings contain the same text?

if (x.get(i) == x.get(j)) {
    return true;
}
Ax.get(i) = x.get(j)
Bx.get(i) == x.get(j)
Cx.get(i).equals(x.get(j))
Dx.get(i).length() == x.size()
Correct answer: C. equals compares the text the two String objects contain, which is what a duplicate check needs.
Explanation

The elements of the list are objects, so the comparison has to look at contents rather than at the objects themselves. The section's hasDup method uses equals for the same reason when its nested loops compare the Integer elements at indexes i and j.

  • A is not correct: One equals sign assigns rather than compares, so this line does not test whether the two elements hold the same text.
  • B is not correct: This repeats the line the question asks you to replace, comparing the objects instead of the text stored inside them.
  • D is not correct: This compares the length of one string with the number of elements in x, which says nothing about whether two elements match.
Q11

Consider the following code segment. If a is [4, 8, 1], what does it contain afterward?

for (int i = a.size() - 1; i >= 1; i--) {
    a.set(i, a.get(i - 1));
}
A[4, 4, 8]
B[8, 1, 1]
C[1, 4, 8]
D[4, 8, 1]
Correct answer: A. Each pass copies the value one position right, so 8 overwrites 1 and then 4 overwrites 8.
Explanation

This is a shift, not a rotation. Because set replaces values at existing indexes, the size does not change, and the old last value is simply overwritten and lost. The loop runs backward from size() - 1 down to 1 so each position is written before its own value is needed as a source.

  • B is not correct: Moving 8 and 1 toward the front would be a left shift; this loop copies values to higher indexes instead.
  • C is not correct: [1, 4, 8] would require saving the old last value and writing it at index 0, which a rotation does and a shift does not.
  • D is not correct: The contents do change, because set writes a new value at index 2 and then another at index 1.
Q12

Assume nums initially contains [2, 4, 6, 8]. What does nums contain afterward?

int last = nums.remove(nums.size() - 1);
nums.add(0, last);
A[2, 4, 6]
B[2, 4, 6, 8]
C[2, 4, 8, 6]
D[8, 2, 4, 6]
Correct answer: D. The indexed remove deletes the final element and returns 8, and add(0, last) then puts that saved value at the front.
Explanation

Indexed removal shifts later elements left and hands back the element it deleted, so [2, 4, 6] remains and 8 is stored in last. Saving the endpoint and writing it at index 0 is exactly the rotate-right idea: no element is lost.

  • A is not correct: The removed value is kept in last and inserted again, so the list does not end up one element shorter.
  • B is not correct: The order does change, because 8 is reinserted at index 0 rather than back at its old position.
  • C is not correct: The insertion index is 0, so 8 moves all the way to the front instead of trading places with its neighbor.
Q13

Assume words initially contains ["sun", "moon", "star"]. What does words contain afterward?

int left = 0;
int right = words.size() - 1;
while (left < right) {
    String temp = words.get(left);
    words.set(left, words.get(right));
    words.set(right, temp);
    left++;
    right--;
}
A[sun, star, moon]
B[star, moon, sun]
C[moon, sun, star]
D[star, sun, moon]
Correct answer: B. The two pointers exchange the first and last elements once, after which left is no longer less than right.
Explanation

This is the in-place reversal with pointers at both ends. Each pass saves one element in temp, writes the other over it, restores the saved value at the far index, then moves left up and right down. With three elements the pointers meet at index 1, so the middle value stays where it is.

  • A is not correct: This leaves "sun" at the front, but the very first swap writes "star" into index 0.
  • C is not correct: This moves the middle element to the front, while the loop only exchanges the outer positions in a three-element list.
  • D is not correct: The ends are exchanged correctly here, but the middle element is never swapped, so "moon" stays at index 1.
Q14

The following code should find the maximum value in a nonempty list. Which replacement for the first statement works when every value may be negative?

int max = 0;
for (int value : nums) {
    if (value > max) {
        max = value;
    }
}
Aint max = -1;
Bint max = nums.size();
Cint max = nums.get(0);
Dint max = -nums.size();
Correct answer: C. Starting the maximum at an actual element of the nonempty list works whether the values are all positive or all negative.
Explanation

For a nonempty list, initialize a minimum or maximum from a real element rather than from an unrelated value, then update it only when the current element is larger. A fixed starting number can never be beaten by a list whose values all sit below it, which is how a wrong answer appears.

  • A is not correct: -1 is still an unrelated value, so a list whose values are all below -1 would report -1 as the maximum.
  • B is not correct: The size counts elements rather than describing them, so it can easily sit above every negative value stored in the list.
  • D is not correct: This is also derived from the number of elements instead of from the data, so it can still exceed every value in the list.