VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-swap-method-in-java-with-examples/

⇱ Collections swap() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections swap() method in Java with Examples

Last Updated : 23 Jan, 2026

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.

  • If both positions are the same, the list remains unchanged
  • Works with ArrayList, LinkedList, Vector, etc.
  • Operates directly on the original list (in-place)

Output
[3, 2, 1]

Explanation: The swap() method exchanges the elements at index 0 and index 2. All other elements in the list remain unchanged.

Syntax 

public static void swap(List<?> list, int i, int j)

Parameters

  • list -The list in which the elements are to be swapped.
  • i - The index of the first element.
  • j - The index of the second element.

Below are the examples to illustrate the swap() method

Example 1: Swapping Elements in a List


Output
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


Output
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.
Comment