How Swap elements of Java LinkedList

This example shows how to How Swap elements of Java LinkedList . This examples also shows How Swap elements of Java LinkedList using collections.swap().

How Swap elements of Java LinkedList?

We will use Collections.swap() method to swap element of linkedlist in java. Collections.swap() method Swaps the elements at the given positions in the specified list.

Syntax :

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

   }

Parameters: This method takes following parameter
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.
Exception Throws: This method throw following exception
IndexOutOfBoundsException – It’s throws if either i or j is out of range (i < 0 || i >= list.size() || j < 0 || j >= list.size()).

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]

We have discussed Java Collections – Collections.swap() Examples . We example also show us  how to swap element of Linkedlist in java.

Leave a Reply

Your email address will not be published. Required fields are marked *

23 − = 17