?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Random ArrayList Adds

APCSA-VY1DYP

Consider the following code segment.

ArrayList<String> list = // assume a list of at least one String with no duplicate values

int randIdx = (int) (Math.random()*list.size());
for (int i=0; i<list.size(); i++)
{
    if (list.get(i).equals(list.get(randIdx)))
        list.add(0, list.get(i));
}

For which of the following cases would executing this code segment result in an error or problem?

A

It always throws an index out of bounds error.

B

It throws an index out of bounds error when randIdx is greater than or equal to the number of elements in list.

C

It gets into an infinite loop once it reaches the randomly generated index.

D

It gets into an infinite loop when randIdx is the last position in list.

E

It gets into an infinite loop when randIdx is equal to 0.