How to swap elements in an ArrayList

In this tutorial we will learn how to swap elements of an ArrayList, we will be using Collections.swap() method to achieve sorting.

Swapping the elements of the ArrayList

  • Create a new arraylist arraylist al1.
  • Add elements to al1 using add() method.
  • Use Collections.swap() method to swap the required elements of al1.

public class SwapArrayListExample 
{
    public static void main(String args[])
    {
        ArrayList al = new ArrayList();
        al.add("Element1");
        al.add("Element2");
        al.add("Element3");
        al.add("Element4");
        al.add("Element5");
        
        //Print elements of the ArrayList before swapping
        System.out.println("**Elements of the ArrayList before swapping**");
        for(String val : al)
            System.out.println(val);
        
        //Sort elements
        Collections.swap(al,2,3);
        
      //Print elements of the ArrayList after swapping
        System.out.println("**Elements of the ArrayList after swapping**");
        for(String val : al)
            System.out.println(val);
    }
}

Output :

**Elements of the ArrayList before swapping**
Element1
Element2
Element3
Element4
Element5
**Elements of the ArrayList after swapping**
Element1
Element2
Element4
Element3
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *