How to Swap Two Elements of Java ArrayList


In this example, let’s see how to swap elements of ArrayList object with swap method of Collections class in Java.

Source Code

package com.beginner.examples;

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

public class SwapArrayListElementExample {

	public static void main(String[] args) {

		ArrayList al = new ArrayList();

		al.add("A");
		al.add("B");
		al.add("C");
		al.add("D");

		System.out.println("al:" + al);
		
		// Use the swap() method in the Collections utility class
		Collections.swap(al, 1, 3);

		System.out.println("After the change of position:" + al);

	}

}

Output:

al:[A, B, C, D]
After the change of position:[A, D, C, B]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments