How to swap ArrayList elements in java ?
Simply calling Collections.swap() method you can swap two elements of the ArrayList. You have to pass the indexes which you need to swap. In this example we just swap to element index 2 to index 5.
package com.tech.mindclues; import java.util.ArrayList; import java.util.Collections; public class SwapArrayListElements { public static void main(String a[]){ ArrayListlist = new ArrayList (); list.add("Mind"); list.add("Clues"); list.add("Java"); list.add("Com"); list.add("Tech"); list.add("Hunt"); list.add("Hagrid"); Collections.swap(list, 2, 5); System.out.println("Results after swap operation:"); for(String str: list){ System.out.println(str); } } }
Results after swap operation: Mind Clues Hunt Com Tech Java Hagrid
post a comment