Wednesday, August 14, 2013

How To Use Swapping Method Of Collections In Java



Collections has swap(List<?>, int, int)  method, which is used to swap the elements at the specified position in the specify list.


Declaration of the Method:

This is the declaration of the method  -  java.util.Collections.swap()


public static void swap(List<?> list,int i,int j)


Parameters:

List - Pass the object of the list in which swapping method is to be performed.
int i - Pass the index of the one element which is to be swapped.
int j - Pass the index of the one element which is to be swapped with given int i index.


Example :


*******************************************************************************

package org.javaIsEasy.collectionPrograms;

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

public class SwapListExample {

 public static void main(String[] args) {
  ArrayList<String> programmingLanguageList=new ArrayList<String>();
  programmingLanguageList.add("PHP");
  programmingLanguageList.add(".NET");
  programmingLanguageList.add("C++");
  programmingLanguageList.add("JAVA");
  programmingLanguageList.add("PERL");

  System.out.println("Display List Before Swapping\n");
  Iterator<String> it=programmingLanguageList.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
  Collections.swap(programmingLanguageList, 0, 3);

  System.out.println("Display List After Swapping\n");
  Iterator<String> itSwapped=programmingLanguageList.iterator();
  while(itSwapped.hasNext())
  {
   System.out.println(itSwapped.next());
  }
 }
}


*******************************************************************************

Output :


*******************************************************************************
Display List Before Swapping

PHP
.NET
C++
JAVA
PERL
Display List After Swapping

JAVA
.NET
C++
PHP
PERL

*******************************************************************************