Collection Swap in Java
Problem
Collections.swap() exchanges the elements at two given index positions in a List directly, without the caller needing a temporary variable to hold one of them during the exchange.
Given a List and two index positions, swap the elements found at those two positions.
Java Program
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionSwap {
public static void main(String[] args) {
List<String> podium = Arrays.asList("Gold", "Silver", "Bronze");
Collections.swap(podium, 0, 2); // exchanges only the elements at these two positions
System.out.println("After swap: " + podium);
}
}Output
Core Logic
Collections.swap() takes care of the usual temp-variable dance internally, so exchanging two positions is a single call instead of three assignment lines.
- 1
podiumholds three elements at indices0,1, and2. - 2
Collections.swap(podium, 0, 2)exchanges whatever is currently at index0with whatever is currently at index2. - 3The element at index
1is untouched, since neither index passed in refers to it. - 4The swap happens in place — the same
podiumreference reflects the new arrangement immediately afterward.
0 and 2 in [Gold, Silver, Bronze] exchanges "Gold" and "Bronze", leaving [Bronze, Silver, Gold] — "Silver" stays put.Key Point: Unlike Collections.reverse() or shuffle(), which touch every element, swap() only ever changes the two positions named — a targeted, constant-time operation rather than a full pass over the list.
Why: swap() only reads and writes the two named index positions directly — it never scans or touches any other element in the list, regardless of the list's size.