Way2Java

Java Swap two elements with swap()

The Collections method swap() is very useful to swap two values in a programming code. For example, the prices of two different dates can be swapped. This method comes into existence with JDK 1.4.

Following is the method signature of swap() method

If the index1 and index2 are same, three will be no affect. If the elements with index numbers of index1 and index2 do not exist, the method throws ArrayIndexOutOfBoundsException.

Example on Java Swap two elements with swap()
import java.util.*;
public class CollectionsSwap
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(50);
    myList.add(10);
    myList.add(20);
    myList.add(40);
    System.out.println("Elements before swap: " + myList);

    Collections.swap(myList, 0,1);
    System.out.println("Elements after 0,1 swap: " + myList); 

    Collections.swap(myList, 2,3);
    System.out.println("Elements after 2,3 swap: " + myList); 
  }
}



Output screenshot of Java Swap two elements with swap()

ArrayList myList = new ArrayList();
myList.add(50);

An ArrayList object myList is created and added some elements with add() method inherited from List interface.

Collections.swap(myList, 0,1);
Collections.swap(myList, 2,3);

The elements of myList with index numbers 0 and 1 and also 2 and 3 are swapped. They are swapped in the original list itself.