Swap elements of Java LinkedList - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

Swap elements of Java LinkedList

LinkedList is doubly-linked list implementation of the List and Deque interfaces.

How to swap elements of Java LinkedList?

This example showyou how to swap elements in the LinkedList. We call Collections.swap() to swap elements of list, and need to pass list, specified index first and last. Collections.swap(list, first,last) Swaps the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.

package com.walking.techie;

import java.util.Collections;
import java.util.LinkedList;

public class LinkedListSwapDemo {

 public static void main(String[] args) {
  LinkedList<String> language = new LinkedList<String>();
  language.add("C");
  language.add("CPP");
  language.add("JAVA");
  language.add("DOTNET");
  language.add("C#");
  language.add("PHP");

  System.out.println("Original language linked list " + language);
  // Swaps the elements at the specified positions in the this list.
  Collections.swap(language, 1, 4);
  System.out.println("Results after swap operation:" + language);

  Collections.swap(language, 1, 3);
  System.out.println("Results after swap operation:" + language);
 }
}

Output of above program is shown below:

Original language linked list [C, CPP, JAVA, DOTNET, C#, PHP]
Results after swap operation:[C, C#, JAVA, DOTNET, CPP, PHP]
Results after swap operation:[C, DOTNET, JAVA, C#, CPP, PHP]

No comments :

Post a Comment