Problem of the Day
Monday, November 30, 2026
Problem:
An ArrayList of Integer values arr contains a series of integers. Which of the following code snippets will remove all of the even integers from the ArrayList?
int i = 0;
while (i < arr.size())
{
if (arr.get(i) % 2 == 0)
{
arr.remove(i);
}
else
{
i++;
}
}for (int i = arr.size() - 1; i >= 0; i--)
{
if (arr.get(i) % 2 == 0)
arr.remove(i);
}for (int i = 0; i < arr.size(); i++)
{
if (arr.get(i) % 2 == 0)
arr.remove(i);
}
- I only
- I and III only
- II and III only
- I, II, and III
The correct answer is b. Removing values from an ArrayList can be tricky. If we're moving forward through the array (as we are with the while-loop), we have to be careful to not skip over any values after removing an element and having all elements shift forward in the ArrayList. It's for this reason that another useful strategy is moving backwards through the array (as we are here with the second for-loop: removed values come off the right side of the array, and don't affect our ongoing evaluation of elements on the left side of the array.