Java ProgramsCollectionsCollection Swap

Collection Swap in Java

beginner·  Collections  ·  Collections Utility

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.

Input
[Gold, Silver, Bronze], positions 0 and 2
Output
After swap: [Bronze, Silver, Gold]

Java Program

Java
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

After swap: [Bronze, Silver, Gold]

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.

How It Works
  1. 1podium holds three elements at indices 0, 1, and 2.
  2. 2Collections.swap(podium, 0, 2) exchanges whatever is currently at index 0 with whatever is currently at index 2.
  3. 3The element at index 1 is untouched, since neither index passed in refers to it.
  4. 4The swap happens in place — the same podium reference reflects the new arrangement immediately afterward.
Swapping indices 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.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

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.

Key Concepts

Collections.swap()Listindex-based access

Related Programs