We can use Collections.swap() method to swap two elements in an arraylist in java. We have to pass the indexes which we need to swap.
Syntax:
Collections.swap(arrayList, element1, element2);
Example:
package com.w3schools; import java.util.ArrayList; import java.util.Collections; public class Test { public static void main(String args[]){ ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("Jai"); arrayList.add("Mahesh"); arrayList.add("Vivek"); arrayList.add("Naren"); arrayList.add("Hemant"); arrayList.add("Vishal"); System.out.println("Actual ArrayList:"+arrayList); Collections.swap(arrayList, 3, 5); System.out.println("Results after swap operation:" + arrayList); } } |
Output
Actual ArrayList:[Jai, Mahesh, Vivek, Naren, Hemant, Vishal] Results after swap operation:[Jai, Mahesh, Vivek, Vishal, Hemant, Naren] |