javacodex.com
Java Examples
Java Examples
memu home questions

Swap Two Elements In An ArrayList

This java example shows how to swap two elements in an ArrayList.

Source: (SwapElements.java)

import java.util.*;
 
public class SwapElements { 
   public static void main(String[] args) { 
      ArrayList list = new ArrayList();
      list.add("John");
      list.add("Ringo");
      list.add("George");
      list.add("Paul");
      System.out.println("ArrayList Before: "+ list);
      Collections.swap(list, 1, 2);
      System.out.println("ArrayList After: "+ list);
   } 
}
 

Output:

# java SwapElements 
ArrayList Before: [John, Ringo, George, Paul]
ArrayList After: [John, George, Ringo, Paul]

Contact: javacodex@yahoo.com