Swap elements of Java ArrayList example

We Swap List element using swap method of    Collections.

import java.util.ArrayList;
import java.util.Collections;

public class SwapElement {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
// print arraylist
System.out.println(“ArrayList Before Swap is = ” + arr);

* Swaps the elements at the specified positions in the specified list.
*  (If the specified positions are equal,
invoking this method leaves the list unchanged.)


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


IndexOutOfBoundsException – if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >=

Collections.swap(arr, 1, 3);

System.out.println(“ArrayList Before Swap is = ” + arr);




ArrayList Before Swap is = [c, php, html, java]

ArrayList Before Swap is = [c, java, html, php]

Related Posts:

Notice: compact(): Undefined variable: limits in /home/javaprof/public_html/wp-includes/class-wp-comment-query.php on line 853

Notice: compact(): Undefined variable: groupby in /home/javaprof/public_html/wp-includes/class-wp-comment-query.php on line 853

Leave a Reply

Your email address will not be published. Required fields are marked *

53 − = 44