Saturday 18 February 2012

swap list elements example


package com.usr.collections;

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

public class SwapList {
       public static void main(String[] args) {
              List<String> list = new ArrayList<String>();
              addElementsToList(list);
              System.out.println("list elements before swaping:");
              displayList(list);
              System.out.println("......................");
              swapList(list);
              System.out.println("list elements after swaping:");
              displayList(list);
       }

       public static void addElementsToList(List<String> list) {
              list.add("one");
              list.add("two");
              list.add("three");
              list.add("four");
              list.add("five");

       }

       public static void swapList(List<String> list) {
              // public static void swap(List<?> list, int i,int j)
              // Swaps the elements at the specified positions in the specified list.
              // (If the specified positions are equal, invoking this method leaves
              // the list unchanged.)
              Collections.swap(list, 2, 4);

       }

       public static void displayList(List<String> list) {
              for (String temp : list) {
                     System.out.println(temp);
              }

       }

}

output 
list elements before swaping:
one
two
three
four
five
......................
list elements after swaping:
one
two
five
four
three

No comments:

Post a Comment

Note: only a member of this blog may post a comment.