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?
The code segment skips some elements of myList because the indexes of all subsequent elements change by one when a list element is removed.
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.
The code segment causes an IndexOutOfBoundsException for all lists because of an incorrect Boolean expression in the for loop.
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.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #2 | y.seong2027 | 1 | 1 | 2m 04s | -24 |
| #3 | ponneban000 | 1 | 2 | 3m 10s | -100 |
| #4 | geethasailaja | 1 | 1 | 4m 55s | -195 |
| #5 | chunxiangxu.cxu | 0 | 1 | 10m 49s | -659 |
| #6 | singhris000 | 1 | 1 | 17m 26s | -946 |
APFIVE