How to Swap Two Elements in an ArrayList in Java

Learn to swap two specified elements in ArrayList in Java. We will use Collections.swap() method to swap two elements within a specified arraylist at specified indices.

1. Collections.swap() API

The Collections.swap() method swaps the elements at the specified positions in the specified list. The index arguments must be a valid index in the list, else method will throw IndexOutOfBoundsException exception.

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

Where –

  • list – The list in which to swap elements.
  • i – the index of one element to be swapped.
  • j – the index of another element to be swapped.

Invoking this method leaves the list unchanged if the specified positions are equal.

2. Swapping Two Elements in ArrayList

The following Java program swaps two specified elements in a given list. In this example, we are swapping the elements at positions ‘1’ and ‘2’. The elements are these positions in the list are ‘b’ and ‘c’.

Please note that indexes start from 0.

ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f"));
Collections.swap(list, 1, 2);

Program output.

[a, b, c, d, e, f]
[a, c, b, d, e, f]

3. Throws IndexOutOfBoundsException

Note that if the specified indices are out of bounds, then the method throws IndexOutOfBoundsException.

Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {
  Collections.swap(list, 10, 11);

The above example is a java program to interchange the element value and its corresponding index values. Let me know if you have any questions.

Happy Learning !!

Read More: ArrayList Java Docs

Sourcecode on Github


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode