Skip to Content

Swap elements of Java ArrayList example

  1. /*
  2.   Swap elements of Java ArrayList example
  3.   This java example shows how to swap elements of Java ArrayList object using
  4.   swap method of Collections class.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9.  
  10. public class SwapElementsOfArrayListExample {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("A");
  19.     arrayList.add("B");
  20.     arrayList.add("C");
  21.     arrayList.add("D");
  22.     arrayList.add("E");
  23.    
  24.     System.out.println("Before swaping, ArrayList contains : " + arrayList);
  25.    
  26.     /*
  27.       To swap elements of Java ArrayList use,
  28.       static void swap(List list, int firstElement, int secondElement)
  29.       method of Collections class. Where firstElement is the index of first
  30.       element to be swapped and secondElement is the index of the second element
  31.       to be swapped.
  32.      
  33.       If the specified positions are equal, list remains unchanged.
  34.      
  35.       Please note that, this method can throw IndexOutOfBoundsException if
  36.       any of the index values is not in range.
  37.     */
  38.    
  39.     Collections.swap(arrayList,0,4);
  40.    
  41.     System.out.println("After swaping, ArrayList contains : " + arrayList);
  42.    
  43.   }
  44. }
  45.  
  46. /*
  47. Output would be
  48. Before swaping, ArrayList contains : [A, B, C, D, E]
  49. After swaping, ArrayList contains : [E, B, C, D, A]
  50. */