![]() |
VOOZH | about |
The swap() method of java.util.Collections is used to exchange elements at two specified positions in a list. It works with any class that implements the List interface.
[3, 2, 1]
Explanation: The swap() method exchanges the elements at index 0 and index 2. All other elements in the list remain unchanged.
public static void swap(List<?> list, int i, int j)
Below are the examples to illustrate the swap() method
Example 1: Swapping Elements in a List
Before swap: [A, B, C, D, E] After swap: [E, B, C, D, A]
Explanation: The swap() method exchanges the elements located at index 0 and index 4 in the list.All remaining elements retain their original positions.
Example 2: IndexOutOfBoundsException
Before swap: [A, B, C, D, E] Exception thrown: java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5
Explanation: The method attempts to swap elements using an index that exceeds the list size. As a result, an IndexOutOfBoundsException is thrown at runtime.
Note:
- swap() operates in constant time for most List implementations.
- The list must be modifiable.
- No changes occur if both indices are the same.
- Useful for sorting algorithms, shuffling, and DSA problems.