ArrayList Traversals FRQ Practice

Responses receive AI feedback against a rubric after submission. Scores are practice estimates.

Question 1 of 5

Complete the missing cells. Then explain whether an enhanced for loop could legally perform these removes.

ArrayList<Integer> bells = new ArrayList<Integer>();
bells.add(2);
bells.add(5);
bells.add(5);
bells.add(2);
for (int i = bells.size() - 1; i >= 0; i--) {
    if (bells.get(i) == 5) {
        bells.remove(i);
    }
}
After statement i bells
loop starts 3 [2, 5, 5, 2]
index 3 is kept
first 5 from the back is removed
loop ends

Question 2 of 5

Write printSlips so each marina code is displayed in stored order with no spaces. Use an indexed for loop and get. Visit every legal index and no illegal one.

public void printSlips(ArrayList<String> slips) {
    /* write this method */
}

Question 3 of 5

Fog readings of 0 are supposed to be deleted.

public void dropZero(ArrayList<Integer> fogs) {
    for (int i = 0; i < fogs.size(); i++) {
        if (fogs.get(i) == 0) {
            fogs.remove(i);
        }
    }
}

(a) Trace dropZero on [0, 0, 4] and give the list after the method returns. (b) Explain why a 0 can remain. (c) Add one statement so consecutive zeros are both removed.

Question 4 of 5

A carnival tries to copy high scores into the same list using an enhanced for loop.

public void echoHigh(ArrayList<Integer> scores) {
    for (Integer n : scores) {
        if (n > 10) {
            scores.add(n);
        }
    }
}

(a) Why can echoHigh throw ConcurrentModificationException? (b) Rewrite it so high scores are appended without using an enhanced for loop on scores while adding. (c) Why must the rewrite not use scores.size() as a growing bound if it adds to the same list?

Question 5 of 5

Compare the two fragments. Fragment P uses get(i) with i <= sizes.size(). Fragment Q removes inside for (Integer x : sizes).

ArrayList<Integer> sizes = new ArrayList<Integer>();
sizes.add(4);
sizes.add(6);

(a) Which exception can fragment P throw, and on which index? (b) Which exception can fragment Q throw? (c) Write a legal enhanced for loop that prints every value in sizes.