Learn AP Comp Sci

☰

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?


  1. int i = 0;
    while (i < arr.size())
    {
    if (arr.get(i) % 2 == 0)
    {
    arr.remove(i);
    }
    else
    {
    i++;
    }
    }

  2. for (int i = arr.size() - 1; i >= 0; i--)
    {
    if (arr.get(i) % 2 == 0)
    arr.remove(i);
    }

  3. for (int i = 0; i < arr.size(); i++)
    {
    if (arr.get(i) % 2 == 0)
    arr.remove(i);
    }
  1. I only
  2. I and III only
  3. II and III only
  4. I, II, and III

Show solution:

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.