How to swap two elements in ArrayList in Java

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

1. Swap two elements in arraylist – Collections.swap()

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.

If the specified positions are equal, invoking this method leaves the list unchanged.

Method syntax

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 other element to be swapped.

2. Swap two elements in arraylist example

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

Please note that indexes start from 0.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f"));
        
        System.out.println(list);
        
        Collections.swap(list, 1, 2);
        
        System.out.println(list);
    }
}

Program output.

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

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

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs