Swapping items of a list in Java : Collections.swap() with Example
java.util.Collections.swap() method is a java.util.Collections class method. It swaps elements at the specified positions in given list.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
// Swaps elements at positions "i" and "j" in myList. public static void swap(List mylist, int i, int j) It throws IndexOutOfBoundsException if either i or j is out of range.
Original List : Original List : [code, practice, quiz, geeksforgeeks] After swap(mylist, 1, 2) : [code, quiz, practice, geeksforgeeks] After swap(mylist, 3, 1) : [code, geeksforgeeks, practice, quiz]
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.