In this article, we will learn how to replace an element in linked list using set()
method. This method is especially useful when we need to replace element at specified index in linked list.
The set() method:
public E set(int index, E newElement)
: This method takes two arguments, index
and newElement
. It replaces the current element at the specified index
with the newElement
.
Java Program to replace an element in a LinkedList
In this program, we have a linked list of string type, we have added few string elements to it. Later, we replaced the 3rd element (present at index 2) with the new value using set()
method.
import java.util.LinkedList; public class ReplaceInLinkedList { public static void main(String[] args) { // Create a LinkedList LinkedList<String> linkedlist = new LinkedList<String>(); // Add elements to LinkedList linkedlist.add("Cobol"); linkedlist.add("JCL"); linkedlist.add("C++"); linkedlist.add("C#"); linkedlist.add("Java"); // Displaying Elements before replace System.out.println("Before Replace:"); for(String str: linkedlist){ System.out.println(str); } // Replacing 3rd Element with new value linkedlist.set(2, "NEW VALUE"); System.out.println("\n3rd Element Replaced \n"); // Displaying Elements after replace System.out.println("After Replace:"); for(String str2: linkedlist){ System.out.println(str2); } } }
Output:
Before Replace:
Cobol
JCL
C++
C#
Java
3rd Element Replaced
After Replace:
Cobol
JCL
NEW VALUE
C#
Java
Leave a Reply