import java.util.Collections;
import java.util.LinkedList;
public class SwapElement {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println("Before Swap Linklist is = "+linkedList);
/*
* 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(linkedList, 2, 4);
System.out.println("After Swap Linklist is = "+linkedList);
}
}
Output:
Before Swap Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]
After Swap Linklist is = [Mumbai, Delhi, Patna, Gao, Noida]
No comments:
Post a Comment