Java swap in list

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.

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)
  • 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 list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f")); System.out.println(list); Collections.swap(list, 1, 2); System.out.println(list);

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.

Источник

Читайте также:  Css flex center block
Оцените статью