Showing posts with label swap arrraylist element. Show all posts
Showing posts with label swap arrraylist element. Show all posts

Sunday, 10 May 2015

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
        arr.add("c");
        arr.add("php");
        arr.add("html");
        arr.add("java");
        // 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.)
         
          Parameters:
       
        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.
      
        Throws:
      
       IndexOutOfBoundsException - if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >=
        list.size()).
         */

        Collections.swap(arr, 1, 3);
       
        System.out.println("ArrayList Before Swap is = " + arr);
       
    }
   
   
}


Output:

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

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



Related Posts: 

 


Storing Java Object In ArrayList