What is the Collections.swap() method in Java?
Collections.swap() is a static method in the Collections class that swaps elements at specified positions in a selected list.
If the value of elements is equal when this method is invoked, the list remains unchanged.
Syntax
The method signature is as follows:
public static void swap(List<?> list, int i, int j)
Parameter and return types
| Parameter | Description |
|---|---|
List<?> list |
The list in which elements are swapped. |
int i |
The index of one element to be swapped. |
int j |
The index of the other element to be swapped. |
The method throws IndexOutOfBoundsException if either i or j is out of range, i.e., the index value is less than zero or greater than the size of the list.
Code
Example 1
The below example shows how to swap the elements at index 0 and 3.
import java.util.*;public class Main {public static void main(String[] args) {List<Integer> integerList = new ArrayList<>();integerList.add(1);integerList.add(2);integerList.add(3);integerList.add(4);System.out.println("List before swapping - " + integerList);Collections.swap(integerList, 0, 3);System.out.println("List after swapping first and last element - " + integerList);}}
Example 2
The following example shows IndexOutOfBoundsException being thrown when any index is less than zero.
import java.util.*;public class Main {public static void main(String[] args) {List<Integer> integerList = new ArrayList<>();integerList.add(1);integerList.add(2);integerList.add(3);integerList.add(4);System.out.println("List before swapping - " + integerList);Collections.swap(integerList, -1, 3);System.out.println("List after swapping first and last element - " + integerList);}}
Example 3
The code below shows IndexOutOfBoundsException being thrown when an index is greater than the size of the input list.
import java.util.*;public class Main {public static void main(String[] args) {List<Integer> integerList = new ArrayList<>();integerList.add(1);integerList.add(2);integerList.add(3);integerList.add(4);System.out.println("List before swapping - " + integerList);Collections.swap(integerList, 0, 4);System.out.println("List after swapping first and last element - " + integerList);}}