CodesJava

Easy learning with example program codes

how to swap two elements in an arraylist java?


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.

Note: ArrayList provides the facility of random access because of it is index based.

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.

Example:

package com.codesjava;
 
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]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap