fork(16) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main {
  5. public static void main(String[] args) throws java.lang.Exception
  6.  
  7.  
  8. {
  9.  
  10. //create an ArrayList object
  11. ArrayList words = new ArrayList();
  12.  
  13. //Add elements to Arraylist
  14. words.add("A");
  15. words.add("B");
  16. words.add("C");
  17. words.add("D");
  18. words.add("E");
  19.  
  20. System.out.println("Before swaping, ArrayList contains : " + words);
  21.  
  22. /*
  23.   To swap elements of Java ArrayList use,
  24.   static void swap(List list, int firstElement, int secondElement)
  25.   method of Collections class. Where firstElement is the index of first
  26.   element to be swapped and secondElement is the index of the second element
  27.   to be swapped.
  28.  
  29.   If the specified positions are equal, list remains unchanged.
  30.  
  31.   Please note that, this method can throw IndexOutOfBoundsException if
  32.   any of the index values is not in range.
  33.   */
  34.  
  35. Collections.swap(words, 0, words.size() - 1);
  36.  
  37. System.out.println("After swaping, ArrayList contains : " + words);
  38.  
  39.  
  40. }
  41. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
Before swaping, ArrayList contains : [A, B, C, D, E]
After swaping, ArrayList contains : [E, B, C, D, A]