Java Collection Tutorial - Java Collections.swap(List <?> list, int i, int j)








Syntax

Collections.swap(List <?> list, int i, int j) has the following syntax.

public static void swap(List <?> list, int i, int j)

Example

In the following code shows how to use Collections.swap(List <?> list, int i, int j) method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*from   w  w  w.  ja  v a2 s.c  om*/


public class Main {
   public static void main(String[] args) {
      // create vector object 
      List<String> vector = new ArrayList<String>();
      
      // populate the vector
      vector.add("1");
      vector.add("2");
      vector.add("3");
      vector.add("4");
      vector.add("from java2s.com");

      System.out.println("Before swap: "+vector);
      
      // swap the elements
      Collections.swap(vector, 0, 4);
      
      System.out.println("After swap: "+vector);
   }
}

The code above generates the following result.