How to swap elements of ArrayList

In this article, we will discuss how to swap elements of List or ArrayList using Collections class’s utility swap() method

 

Swapping 2 elements of Java ArrayList:

Method signature:

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

In below example,

  • we will swap element at index position-2 with element at index position-6
  • printing ArrayList contents before and after swap
  • iterating ArrayList using enhanced for-loop or forEach

Throws: IndexOutOfBoundsException for index out of range i.e.; 0 > index-position >= al.size();

 

Swap2ElementsOfJavaArrayList.java

package in.bench.resources.java.collection;

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

public class Swap2ElementsOfJavaArrayList {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Narayan Murthy");
		al.add("Dinesh");  
		al.add("Nandan Nilekeni");  
		al.add("Ashok Arora");
		al.add("Shibulal");
		al.add("Kris Gopalakrishnan");
		al.add("Raghavan");

		System.out.println("Before Swap: Iterating"
				+ " ArrayList values as per Insertion Order\n");

		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}

		// swapping elements of ArrayList using Collections.sort(al);
		// element-3 (index-2) with element-7 (index-6) 
		Collections.swap(al, 2, 6);

		System.out.println("\n\nAfter Swap: "
				+ "index position 2nd with 6th\n");

		// Iterating using enhanced for-loop
		for(String str : al){
			System.out.println(str);
		}
	}
}

Output:

Before Swap: Iterating ArrayList values as per Insertion Order

Narayan Murthy
Dinesh
Nandan Nilekeni
Ashok Arora
Shibulal
Kris Gopalakrishnan
Raghavan


After Swap index position 2nd with 6th

Narayan Murthy
Dinesh
Raghavan
Ashok Arora
Shibulal
Kris Gopalakrishnan
Nandan Nilekeni

Note: index position starts with 0 (i.e.; zero-based index)

 

References:

 

Happy Coding !!
Happy Learning !!

How to copy elements of one ArrayList to another List
How to get synchronized version Collection