Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collections.swap — swap two elements in a list

`Collections.swap` exchanges the elements at two indices in the same list. It does not create a new list and requires the list to support `set`.

Version: Java SE 21

Syntax

public static void swap(List<?> list, int i, int j)

Collections.swap(list, i, j) is a static method on java.util.Collections, available since Java 1.4. It accepts List<?>, so the caller does not need to know the element type. It selects elements by index, not by value. It changes the same list without changing its size, creates no new list, and returns nothing (void).

Indices start at 0. Both must be nonnegative and less than list.size(). The API specifies IndexOutOfBoundsException for an out-of-range index. If the list does not support set, however, the call may throw UnsupportedOperationException instead. Passing null as the list causes NullPointerException.

Swapping needs List.set, not add or remove. A fixed-size list from Arrays.asList therefore supports swapping, whereas an unmodifiable list from List.of throws UnsupportedOperationException when asked to swap two distinct valid positions. Equal valid indices leave the order unchanged, but a list that does not support set may still throw UnsupportedOperationException on that call.

To swap the first and last elements, use indices 0 and list.size() - 1. Skip the call if the list has fewer than two elements: an empty list has no valid index, and a one-element list needs no change. The helper mutates the supplied list without making a copy.

Examples

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

public class SwapDemo {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>(List.of("A", "B", "C"));
        List<String> sameList = items;

        System.out.println(items);
        swapEnds(items);
        System.out.println(sameList);
    }

    private static void swapEnds(List<?> list) {
        if (list.size() >= 2) {
            Collections.swap(list, 0, list.size() - 1);
        }
    }
}

Result

[A, B, C]
[C, B, A]

`main` prepares a modifiable `ArrayList`. `sameList` refers to the same list as `items`, so the second print shows `[C, B, A]` through the reference saved before the call.

Related lessons

  • Java · Lesson 12 · Advanced · Version: 2

Sources