Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
medium Solved by 5 students

ArrayList Removal During Iteration

< Prev
Next >

Consider the following method, which is intended to remove all even integers from myList.

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 method does not work as intended?

A

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.

B

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

C

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.

D

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

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question
Mark for review

Question Leaderboard

Rank
User
Correct Count
Attempt Count
Total Time
Score
#1kaisuki11 0m 00s 100
#2y.seong202711 2m 04s -24
#3ponneban00012 3m 10s -100
#4geethasailaja11 4m 55s -195
#5chunxiangxu.cxu01 10m 49s -659
#6singhris00011 17m 26s -946
Items per page:
10
1 – 6 of 6
No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|FAQ