Java - Replace an item in LinkedList
In this tutorial, we'll see how search for an item in a LinkedList and replace it with another new value. In other words, modifying an element to a specific position.The LinkedList class has the following predefined method:
public E set(index position, E element): replaces the element at a given position with another element.
Example:
import java.util.LinkedList;Output:
public class Replace {
public static void main(String[] args) {
LinkedListlinkedlist = new LinkedList ();
linkedlist.add("java");
linkedlist.add("C++");
linkedlist.add("C");
linkedlist.add("php");
linkedlist.add("html");
linkedlist.add("C#");
// before modification
System.out.println("Before permutation:");
for(String str: linkedlist){
System.out.println(str);
}
System.out.println("\n");
// permutation of elements 1 and 2
//temporary variable
String elm = linkedlist.get(1);
linkedlist.set(1, linkedlist.get(2));
linkedlist.set(2, elm);
System.out.println("Swap between C and C++\n");
// LinkedList after modification
System.out.println("After modification:");
for(String elm1: linkedlist){
System.out.println(elm1);
}
}
}
Before permutation:
java
C++
C
php
html
C#
Swap between C and C++
After modification:
java
C
C++
php
html
C#