public class Rotator { /** Precondition: list.size() > 0 */ public static void rotateRight(ArrayList list) { Integer last = list.remove(list.size() - 1); list.add(0, last); } }
An ArrayList named data contains [10, 20, 30, 40, 50]. What are the contents of data after the call Rotator.rotateRight(data)?
- [20, 30, 40, 50, 10]
- [10, 20, 30, 40]
- [50, 10, 20, 30, 40] (correct answer)
- [50, 20, 30, 40, 10]
Explanation: The method performs a right rotation. The last element (50) is removed from the end of the list, which becomes [10, 20, 30, 40]. Then, the removed element (50) is inserted at index 0. The final state of the list is [50, 10, 20, 30, 40].