The swap() method of java.util.Collections is used to exchange elements at two specified positions in a list. It works with any class that implements the List interface.
- If both positions are the same, the list remains unchanged
- Works with ArrayList, LinkedList, Vector, etc.
- Operates directly on the original list (in-place)
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
Collections.swap(list, 0, 2);
System.out.println(list);
}
}
Output
[3, 2, 1]
Explanation: The swap() method exchanges the elements at index 0 and index 2. All other elements in the list remain unchanged.
Syntax
public static void swap(List<?> list, int i, int j)
Parameters
- list -The list in which the elements are to be swapped.
- i - The index of the first element.
- j - The index of the second element.
Below are the examples to illustrate the swap() method
Example 1: Swapping Elements in a List
import java.util.*;
public class GFG1 {
public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
System.out.println("Before swap: " + list);
Collections.swap(list, 0, 4);
System.out.println("After swap: " + list);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown: " + e);
}
}
}
Output
Before swap: [A, B, C, D, E] After swap: [E, B, C, D, A]
Explanation: The swap() method exchanges the elements located at index 0 and index 4 in the list.All remaining elements retain their original positions.
Example 2: IndexOutOfBoundsException
import java.util.*;
public class GFG2 {
public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
System.out.println("Before swap: " + list);
Collections.swap(list, 0, 5);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown: " + e);
}
}
}
Output
Before swap: [A, B, C, D, E] Exception thrown: java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5
Explanation: The method attempts to swap elements using an index that exceeds the list size. As a result, an IndexOutOfBoundsException is thrown at runtime.
Note:
- swap() operates in constant time for most List implementations.
- The list must be modifiable.
- No changes occur if both indices are the same.
- Useful for sorting algorithms, shuffling, and DSA problems.