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