Learn AP Comp Sci

Problem of the Day

Wednesday, April 1, 2026


Problem:

Consider the following method, which is intended to take a value from an ArrayList at position n and move it to the end of the ArrayList, leaving the other items in their original order.

/**
* Moves the item at index n to the end of the ArrayList, leaving
* the other items in their original order
* @param nums an ArrayList of Integers
* @param n an index value indicating which item should be moved
* to the end of the list
* PRECONDITION: The ArrayList has a length > 0.
* PRECONDITION: n is a legal index
*/
public static void endOfTheLine(ArrayList nums, int n)
{
/* missing code */
}

Which of the following could be used to replace /* missing code */ so that the method will work as intended?


  1. nums.remove(n);
    nums.add(n);

  2. int tmp = nums.get(n);
    for (int i = n; i < nums.size() - 1; i++)
    nums.set(i, nums.get(i + 1));
    nums.set(nums.size() - 1, tmp);

  3. nums.add(nums.get(n));
    nums.remove(n);
  1. I only
  2. I and II only
  3. II only
  4. II and III only
  5. I, II, and III

Show solution:

The correct answer is d. Both choice II and III will work as intended. The first choice, I, incorrectly adds the index to the end of the ArrayList rather than the value at that position.