Java Collections swap() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Collections

Definition

In Java, Collections.swap(list, i, j) exchanges the element at index i with the element at index j. Everything else in the list stays where it is. The method returns nothing.

It saves you the three-line "temporary variable" dance. If i and j are equal, the list does not change. It is also the building block that shuffle uses internally.

A static method of the java.util.Collections utility class, available since Java 1.4. Call it on the class name, as in Collections.swap(...), after import java.util.Collections;. You never create a Collections object.

Syntax

Pass the list and the two positions to exchange.

Java
List<String> seats = new ArrayList<>(Arrays.asList("Ann", "Bob", "Cat"));
Collections.swap(seats, 0, 2);   // [Cat, Bob, Ann]
Collections.swap(seats, 1, 1);   // no change
CallWhat it does
Collections.swap(list, i, j)Elements at i and j trade places.
Collections.swap(list, 0, list.size() - 1)First and last trade places.
Collections.swap(list, i, i)Allowed; nothing changes.
Collections.swap(Arrays.asList(arr), i, j)Swaps inside an object array.

Internally it is one line: list.set(i, list.set(j, list.get(i))). set returns the old value, which is what makes the exchange work without a temporary variable.

Library declarations
Java
// java.util.Collections
public static void swap(List<?> list, int i, int j)

Parameters

ParameterDescription
listThe list in which to swap elements.
iIndex of one element.
jIndex of the other element.

Return Value

Return ValueDescription
voidNothing. The two elements have traded places.

Compare with Similar Methods

Other ways to move elements around:

MethodHow it differs
rotate(list, d)Moves every element by the same distance.
reverse(list)Swaps all mirror pairs at once.
shuffle(list)Performs many random swaps.
list.set(i, e)Replaces one element; the old value is lost unless you keep it.

Java Examples

Example 1 — Swap the First and Last Player

Move the last player to the front and the first to the back in one call.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsSwapEnds {
    public static void main(String[] args) {
        List<String> order = new ArrayList<>(Arrays.asList("Ann", "Bob", "Cat", "Dan"));
        System.out.println("Before: " + order);

        Collections.swap(order, 0, order.size() - 1);
        System.out.println("After:  " + order);
    }
}

How It Works

  1. Computed last index. order.size() - 1 is 3, the position of Dan.
  2. One exchange. Ann (index 0) and Dan (index 3) trade places.
  3. Middle untouched. Bob and Cat keep indexes 1 and 2.

Example 2 — Write a Selection Sort with swap()

Find the smallest remaining number on each pass and swap it into place, printing the list after each pass.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsSwapSelection {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(Arrays.asList(5, 3, 4, 1, 2));

        for (int pass = 0; pass < nums.size() - 1; pass++) {
            int minIndex = pass;
            for (int k = pass + 1; k < nums.size(); k++) {
                if (nums.get(k) < nums.get(minIndex)) {
                    minIndex = k;
                }
            }
            Collections.swap(nums, pass, minIndex);
            System.out.println("Pass " + pass + ": " + nums);
        }
    }
}

How It Works

  1. Pass 0. The smallest value, 1, is at index 3; swapping indexes 0 and 3 moves 5 to where 1 was.
  2. Pass 1. Among 3, 4, 5, 2 the minimum is 2 at index 4, so it trades places with the 3 at index 1.
  3. Passes 2 and 3. 3 swaps with the 4 at index 2, then 4 swaps with the 5 at index 3.
  4. Why it stops early. After four passes, the last element must already be the largest, so the loop runs to size() - 2 only.

Example 3 — An Index Past the End

Swapping with a position that does not exist throws, and the list is left as it was.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsSwapBounds {
    public static void main(String[] args) {
        List<Character> chars = new ArrayList<>(Arrays.asList('x', 'y', 'z'));

        Collections.swap(chars, 2, 2);
        System.out.println("Same index: " + chars);

        try {
            Collections.swap(chars, 1, 5);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Index 5: " + e.getClass().getSimpleName());
        }
        System.out.println("Unchanged: " + chars);
    }
}

How It Works

  1. Swapping with itself. swap(chars, 2, 2) writes z back into index 2, so nothing visible changes.
  2. Only indexes 0 to 2 exist. The list has three characters, so index 5 is out of range.
  3. No half-done swap. The failing set at index 5 happens before anything is written, so the list still reads x, y, z.

Frequently Asked Questions

It exchanges the elements at two indexes of a List. All other elements stay in place.
Nothing changes. The element is written back to the same position.
IndexOutOfBoundsException, when an index is negative or not less than the list size.
Yes, for object arrays: Collections.swap(Arrays.asList(array), i, j) swaps inside the array. Primitive arrays such as int[] need a manual swap.
Yes, but each get and set walks the list, so it is slower than on an ArrayList for large lists.

Next: synchronizedCollection()

Wrap any Collection so each method call is thread-safe.

synchronizedCollection() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful