| preferred AP College board partner for AP classes
AP Computer Science A/Unit 7: ArrayList
Start Practice Test
Share
medium Solved by 7 students
ArrayList Removal During Iteration
< Prev
Next >

Consider the following method, which is intended to return a list containing the elements of the parameter myList with all even elements removed.

public static ArrayList<Integer> removeEvens(ArrayList<Integer> myList)
{
    for (int i = 0; i < myList.size(); i++)
    {
        if (myList.get(i) % 2 == 0)
        {
            myList.remove(i);
        }
    }
    return myList;
}

Which of the following best explains why the code segment does not work as intended?

A

The code segment causes an IndexOutOfBoundsException for all lists because of an incorrect Boolean expression in the for loop.

B

The code segment causes an IndexOutOfBoundsException for lists with at least one even element because the indexes of all subsequent elements change by one when a list element is removed.

C

The code segment skips some elements of myList because the indexes of all subsequent elements change by one when a list element is removed.

D

The code segment removes the wrong elements of myList because the condition in the if statement to test whether an element is even is incorrect.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Time
Score
#1kaisuki11 0m 00s 100
#2y.seong202711 2m 04s -24
#3ponneban00012 3m 10s -100
#4geethasailaja11 4m 55s -195
#5singhris00011 17m 26s -946
APFIVE © 2020.
Email: [email protected]|Privacy Policy