AP Computer Science A • Unit 4.9

ArrayList Traversals

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

Q1A
Q2D
Q3B
Q4C
Q5B
Q6B
Q7A
Q8C
Q9A
Q10D
Q11B
Q12A
Q13C
Q14D
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 condition visits every valid index of list?

Ai < list.size()
Bi <= list.size()
Ci < list.length
Di <= list.length()
Correct answer: A. Valid access indexes stop at size() - 1, so an indexed traversal uses < against list.size().
Explanation

An ArrayList reports its length with list.size() and reaches its elements with list.get(i). Because counting starts at 0, the last stored element sits at size() - 1, and a strict < is exactly what stops the loop there.

  • B is not correct: Using <= lets the loop run one step past the last element, so its final access is list.get(list.size()), an index where no element exists.
  • C is not correct: length without parentheses is how an array reports its length, as in array.length; an ArrayList reports its length through size() instead.
  • D is not correct: This mixes the wrong length name with the wrong comparison, so even if the length were read correctly the <= would still push the traversal past the final valid index.
Q2

Which header reads every String in labels?

Afor (int label : labels)
Bfor (labels : String label)
Cfor (String label = labels)
Dfor (String label : labels)
Correct answer: D. An enhanced for header names the element type, then the loop variable, then a colon, then the list being traversed.
Explanation

The loop variable receives one element reference at a time and provides no index. Because labels holds String references, the variable that receives each element must be declared as a String.

  • A is not correct: The loop variable is declared as an int, but each element handed to it is a String reference, so the variable cannot receive the values being traversed.
  • B is not correct: The list name and the declared loop variable are swapped, so nothing in the header declares the variable that is supposed to receive each element.
  • C is not correct: An enhanced for separates the loop variable from the list with a colon; an assignment with = would try to store the whole list in one String variable.
Q3

A loop must visit elements at indexes 2 through the end. Which traversal feature is needed?

AA fixed list size
BAn index that starts at 2
CAn enhanced for variable named 2
DA call to remove(2)
Correct answer: B. Starting at index 2 is a statement about position, and only an indexed traversal lets you choose the starting index.
Explanation

The section says to choose the loop from the task. When the algorithm cares about positions rather than about every value in turn, an indexed for or while loop is the pattern, because its counter can be initialized wherever the ordered sequence begins.

  • A is not correct: Whether the size stays fixed says nothing about where the traversal begins; a list of unchanging size can still be visited from index 0.
  • C is not correct: An enhanced for variable holds an element reference and does not provide an index at all, so naming it cannot make the traversal begin at a position.
  • D is not correct: remove(2) deletes that element and shifts every later element one position left, which changes the list instead of visiting an ordered sequence of it.
Q4

Assume points contains [2, 5, 4]. What is the value of total?

int total = 0;
for (int point : points) {
    total += point;
}
A2
B5
C11
DThe code does not compile.
Correct answer: C. The enhanced for loop hands each stored value to point in turn, so total accumulates 2, then 5, then 4.
Explanation

This is the read-without-resizing pattern: the loop needs each element value, and it neither adds nor removes elements. Every element is visited exactly once, so the running sum ends at the sum of all three values.

  • A is not correct: That is the total after only the first iteration; the loop does not stop after one element, it continues through the ordered sequence.
  • B is not correct: That is a single element value rather than a running total, and total += point keeps adding rather than replacing what is stored.
  • D is not correct: The header declares the loop variable with a type, a name, a colon, and the list, which is the enhanced for form the section shows for reading every element.
Q5

If i == data.size(), what does data.get(i) cause?

AThe last element is returned.
BAn IndexOutOfBoundsException
Cnull is returned.
DThe first element is returned.
Correct answer: B. Index size() is one past the last valid index, and no element exists there.
Explanation

Valid access indexes run from 0 through size() - 1. This is exactly the failure the section describes for names.get(names.size()), and it is why an indexed traversal must use < rather than <=.

  • A is not correct: The last element is at size() - 1, so asking for size() requests a position past it rather than the final stored element.
  • C is not correct: Nothing is quietly handed back for an index with no element; Java throws instead of letting the traversal continue with a placeholder value.
  • D is not correct: Indexes do not wrap around to the front of the list, so running one past the end does not restart the traversal at index 0.
Q6

During enhanced for, items.remove(item) executes. What can occur?

AArithmeticException
BConcurrentModificationException
CThe list becomes an array.
DThe removal is always ignored.
Correct answer: B. Removing an element during an enhanced for loop is a structural change to the list, and that can cause a ConcurrentModificationException.
Explanation

The enhanced for pattern is for reading values while the list size stays the same. Adding or removing an element during the traversal changes the size and the indexes underneath the loop, which is the situation this exception reports.

  • A is not correct: This traversal performs no arithmetic that could fail; the problem is the change to the list structure while the loop is still walking it.
  • C is not correct: A list does not turn into an array because an element was removed; ArrayList and arrays stay separate, one using size() and the other using length.
  • D is not correct: The removal is not silently discarded; the danger is precisely that it takes effect and changes the size during the traversal.
Q7

Assume codes contains at least one element. Consider the following code segment. Which statement is true?

for (String code : codes) {
    codes.set(0, "X");
}
Aset does not change the list size.
BThe loop adds one element per iteration.
CThe loop removes the first element.
Dset changes codes into an array.
Correct answer: A. set replaces an element that already exists, so the number of elements stays the same during the traversal.
Explanation

The section separates structural change from replacement. Adding or removing elements inside an enhanced for loop is what risks a ConcurrentModificationException; replacing an existing element does not change the size, though indexed traversal is clearer when replacement is the goal.

  • B is not correct: Nothing here adds an element; set writes over the element already stored at index 0 rather than making the list longer.
  • C is not correct: No removal happens either, so the element at index 0 is overwritten in place and no later element shifts left.
  • D is not correct: Replacing a stored element leaves the list an ArrayList, which is still accessed with size() and get.
Q8

Assume a contains [4, 4, 9]. Consider the following code segment. What is printed?

int k = 0;
while (k < a.size()) {
    if (a.get(k) == 4) {
        a.remove(k);
    }
    k++;
}
System.out.println(a.get(0) + " " + a.size());
A9 1
B4 3
C4 2
DAn index error occurs.
Correct answer: C. The loop always increments k, so after the first 4 is removed the second 4 shifts into that index and is skipped, leaving [4, 9].
Explanation

When remove(k) deletes an element, every later element shifts one position left, so the next unvisited element is now at index k. Advancing k anyway steps over it, exactly like the section's [0, 0, 4] example that ends as [0, 4].

  • A is not correct: This assumes both 4 values were deleted, but the second one slid into the index the loop had just left behind and was never tested.
  • B is not correct: The list does not keep all three elements; one 4 is genuinely removed, so the size drops before the printing statement runs.
  • D is not correct: The condition k < a.size() is rechecked against the shrinking size each pass, so the loop stops in bounds and a.get(0) is a valid access.
Q9

In a controlled forward-removal loop, when should the index increase?

AOnly when the current element is kept
BImmediately after every removal
COnly when the list is empty
DBefore the condition is tested
Correct answer: A. In the controlled forward pattern the index advances only in the branch where nothing was removed.
Explanation

After a removal the later elements shift one position left, so the next unvisited element already occupies the current index. Leaving the index alone lets the loop test that shifted element on the following pass instead of stepping over it.

  • B is not correct: Advancing right after a removal is the mistake itself, because it moves past the element that just shifted into the current index.
  • C is not correct: The loop must keep moving through elements while they are being kept; waiting for an empty list would leave the traversal stuck on one index.
  • D is not correct: The condition is what decides whether another pass happens at all, so changing the index ahead of it is not what separates a kept element from a removed one.
Q10

Which header traverses a backward?

Afor (int i=0; i<a.size(); i++)
Bfor (int i=a.size(); i>=0; i--)
Cfor (int i=0; i<=a.size(); i++)
Dfor (int i=a.size()-1; i>=0; i--)
Correct answer: D. A backward traversal starts at the last valid index, a.size() - 1, and counts down while the index is at least 0.
Explanation

This is the safe removal pattern from the section. A backward loop has already visited the higher indexes that a removal shifts, and the lower indexes it still has to visit stay in place.

  • A is not correct: This counts upward from 0, which is the forward pattern, and forward removal is what risks skipping a shifted element.
  • B is not correct: Counting down is right, but the first access uses index a.size(), where no element exists, so it can cause an IndexOutOfBoundsException.
  • C is not correct: This moves forward and its condition uses <=, so its final access is one past the last valid index.
Q11

After list.remove(2), what happens to the element previously at index 3?

AIt remains at index 3.
BIt moves to index 2.
CIt moves to index 4.
DIt is automatically removed.
Correct answer: B. Removal shifts every later element one position left, so the element that was at index 3 now sits at index 2.
Explanation

This shifting is why the list's indexes change whenever the size changes. It is also the reason a forward loop that always advances can skip an element: the next unvisited element has moved into the index the loop is about to leave.

  • A is not correct: Positions after the removed element do not stay fixed; the list closes the gap, which is what makes the indexes change.
  • C is not correct: Elements shift toward the front when one is deleted, not away from it; moving to a higher index would leave a hole in the list.
  • D is not correct: Only the element named by remove(2) is deleted; the elements after it survive and simply move down one position.
Q12

Assume Job has an isReady method. What does the condition test?

if (jobs.get(i).isReady()) {
    readyCount++;
}
AThe object at index i
BThe list size
CEvery object at once
DThe value of readyCount
Correct answer: A. jobs.get(i) returns the object stored at index i, and isReady is then called on that one object.
Explanation

Read list.get(i).method() from left to right: get the current object, then ask that object for the answer. The section shows the same reading with names.get(i).length() and with a Learner returned by learners.get(i) calling getName().

  • B is not correct: The size of the list comes from size(); get(i) hands back a single stored element rather than a count.
  • C is not correct: Only the element at the current index is tested on this pass, which is why the surrounding traversal has to visit the indexes one at a time.
  • D is not correct: readyCount is only updated inside the body; the condition asks the retrieved Job object about itself.
Q13

Assume v contains [6, -1, 3, -2]. Consider the following code segment. What is printed?

for (int i=v.size()-1; i>=0; i--) {
    if (v.get(i) < 0) {
        v.remove(i);
    }
}
System.out.println(v.get(0) + " " + v.get(1));
System.out.println(v.size());
A6 -1, then 3
B-1 -2, then 2
C6 3, then 2
DAn index error occurs.
Correct answer: C. Counting down from the last index removes both negative values without skipping either, leaving [6, 3], so the prints show 6 3 and then 2.
Explanation

A backward loop has already visited the higher indexes that a removal shifts left, and the lower indexes it will visit next are untouched by the shift. That is what makes backward traversal a safe removal strategy.

  • A is not correct: This keeps a negative value in the list and reports a size of three, but the loop removes an element every time v.get(i) is negative.
  • B is not correct: The negative values are the ones being deleted, so they cannot be what remains at indexes 0 and 1 when the printing runs.
  • D is not correct: The loop starts at v.size() - 1 and stops at 0, and two elements remain afterward, so both v.get(0) and v.get(1) are valid.
Q14

Consider the following loop header. Which change prevents the final access from using an invalid index?

for (int i = 0; i <= records.size(); i++) {
AStart i at 1.
BReplace i++ with i--.
CReplace size() with get(i).
DReplace <= with <.
Correct answer: D. Changing <= to < stops the loop at size() - 1, which is the last valid index.
Explanation

With <= the final pass uses index records.size(), where no element exists, and that access throws an IndexOutOfBoundsException. A strict < is the standard indexed traversal condition for exactly this reason.

  • A is not correct: Starting at 1 skips the element at index 0 and still lets the loop run through size(), so the invalid final access remains.
  • B is not correct: Counting down from 0 moves away from the elements instead of through them, and it does not address the condition that permits index size().
  • C is not correct: The condition needs the number of elements, which comes from size(); get(i) retrieves an element and is what fails on the invalid index.