Collections swap() method in Java with Examples
The swap() method of java.util.Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.
public static void swap(List list, int i, int j)
Parameters: This method takes the following argument as a Parameter
- list – The list in which to swap elements.
- i – the index of one element to be swapped.
- j – the index of the other element to be swapped.
Exception This method throws IndexOutOfBoundsException, if either i or j is out of range (i = list.size() || j = list.size()).
Below are the examples to illustrate the swap() method
Before swap: [A, B, C, D, E] Swapping 0th and 4th element. After swap: [E, B, C, D, A]
Example 2: For IndexOutOfBoundsException
Before swap: [A, B, C, D, E] Trying to swap elements more than upper bound index Exception thrown : java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
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.