Collections.reverse: Reversing List Order
You'll learn how Collections.reverse() flips a list in-place by swapping elements from opposite ends toward the center.
What Is Collections.reverse?
The Collections.reverse() method takes a list and reverses its order by physically swapping elements. Unlike sorting, which arranges elements by comparison, reversing simply flips the sequence: the first element becomes the last, the second becomes second-to-last, and so on.
Think of it like flipping a line of people: the person at the front walks to the back, the person at the back walks to the front, and they meet in the middle.
How It Works
Collections.reverse() modifies the list in-place—it doesn't create a new list. The algorithm swaps elements from both ends, moving toward the center:
- Swap element at index 0 with element at index n-1
- Swap element at index 1 with element at index n-2
- Continue until reaching the middle
For a list with 5 elements, it performs 2 swaps (the middle element stays put). For 6 elements, it performs 3 swaps.
Code Example
import java.util.*;
public class ReverseDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie", "Diana"));
System.out.println("Before: " + names);
Collections.reverse(names);
System.out.println("After: " + names);
// Output: [Diana, Charlie, Bob, Alice]
}
}
Practical Considerations
Since reverse() modifies the list in-place, the list must be modifiable. Attempting to reverse an immutable list throws UnsupportedOperationException.
Key Takeaway: Collections.reverse() efficiently reverses a list in-place by swapping elements from both ends toward the center, requiring only n/2 swap operations.