Answer:In order to swap elements of ArrayList with Java collections, we need to use the Collections.swap() method. It swaps the elements at the specified positions in the list.
Declaration −The java.util.Collections.swap() method is declared as follows
public static void swap(List <?> list, int i, int j)
where i is the index of the first element to be swapped, j is the index of the other element to be swapped and list is the list where the swapping takes place.
Explanation:
import java.util.*;
public class Example {
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);//0
list.add(20);//1
list.add(30);//2
list.add(40);//3
list.add(50);//4
System.out.println("Original list : " + list);
Collections.swap(list, 4, 0); // swapping element at index 3 i.e. 50 and index 1 i.e. 10
System.out.println("List after swapping : " + list);
}
}