In the last post we shared a tutorial on searching an element in LinkedList. Here we are gonna see how to replace an existing element value with the new value in LinkedList using the index of the element.
Example
The method we used in the below program is:
public E set(int index, E element)
: Replaces the element at the specified position in this list with the specified element.
Complete code:
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