Collections public static void swap(List list, int i, int j) Method Example Program


Swaps the elements at the specified positions in the specified list.

Program

package com.candidjava;

import java.util.Collections;
import java.util.Vector;

/**
 * 
 * @author karthikeyan.T
 * @description Collections: swap(List list, int i, int j) 
 */

public class CollectionsSwap {
	public static void main(String[] args) {
		Vector<String> v = new Vector<String>();
		v.add("Karthik");
		v.add("Kamal");
		v.add("Mohan");
		v.add("Anand");
		v.add("Vinodh");
		System.out.println(v);
		Collections.swap(v, 0, 4);
		System.out.println(v);
	}
}

Output

[Karthik, Kamal, Mohan, Anand, Vinodh]
[Vinodh, Kamal, Mohan, Anand, Karthik]

Explanation

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.)
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()).
Since:
1.4


Related Post

Comments


©candidjava.com