java.util.Collections.swap() method is a java.util.Collections class method. It swaps elements at the specified positions in given list.
// 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.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Randomly select items from a List in Java
- Swapping Characters of a String in Java
- Swapping Pairs of Characters in a String in Java
- How to add all items from a collection to an ArrayList in Java?
- How to add selected items from a collection to an ArrayList in Java?
- Java 8 | DoubleToIntFunction Interface in Java with Example
- Program to convert List of Integer to List of String in Java
- Program to convert List of String to List of Integer in Java
- How to iterate over a 2D list (list of lists) in Java
- Arrays.deepToString() in Java with Example
- NavigableMap Interface in Java with Example
- Deque interface in Java with Example
- StringTokenizer class in Java with example | Set 1 ( Constructors)
- Collections.singleton() method in Java with example
- java.util.Currency methods with example
- Beginning Java programming with Hello World Example
- Serialization and Deserialization in Java with Example
- Java Math asin() method with Example
- Map.Entry interface in Java with example
- Arraylist lastIndexOf() in Java with example