Write a Java program to swap two elements in an array list


This is a Java program that swaps two elements in an ArrayList of Strings using the Collections.swap method. Here's how the program works:

  • The program creates an ArrayList of Strings, named list_col, and initializes it with some values.
  • The program prints the contents of list_col using a for-each loop and System.out.println.
  • The program uses the Collections.swap method to swap the second and fifth elements of list_col. The Collections.swap method takes three arguments: the list in which the swap is to be performed, the index of the first element to be swapped, and the index of the second element to be swapped.
  • The program prints the contents of list_col again using a for-each loop and System.out.println.

Source Code

import java.util.ArrayList;
import java.util.Collections;
public class Swap_ArrayList
{
	public static void main(String[] args)
	{
		ArrayList<String> list_col= new ArrayList<String>();
		list_col.add("Black");
		list_col.add("Orange");
		list_col.add("Pink");
		list_col.add("Blue");
		list_col.add("White");
		list_col.add("Yellow");	
 
		System.out.println("Array List before Swap : ");
		for(String a: list_col)
		{
			System.out.println(a);
		}
 
		Collections.swap(list_col, 1, 4);
		System.out.println("Array List after swap : ");
		for(String b: list_col)
		{
			System.out.println(b);
		}
	}
}

Output

Array List before Swap :
Black
Orange
Pink
Blue
White
Yellow
Array List after swap :
Black
Orange
White
Blue
Pink
Yellow

Example Programs