Java Collections swap() Method
Example
Swap the first item and the last item in a list:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Collections.swap(cars, 0, 3);
System.out.println(cars);
}
}
Definition and Usage
The swap() method swaps two items in a list. The item at the first index moves to the second index, and the item at the second index moves to the first index.
Syntax
public static void swap(List list, int i, int j)
Parameter Values
| Parameter | Description |
|---|---|
| list | Required. The list with the items to swap. |
| i | Required. The index of one item to swap. |
| j | Required. The index of the other item to swap. |
Technical Details
| Returns: | No return value. |
|---|---|
| Throws: | IndexOutOfBoundsException - if i or j is outside the list. |
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods