Write a Java program to Replace an element at a specific position of a LinkedList with the given element


The code demonstrates the replacement of an element at a specific position in a LinkedList in Java. The Replace_Position class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statement is used to print the initial state of the list linked list. Then, the set method is used to replace the element at index 1 (second element) in the list linked list with the string "Watermelon". The set method takes two parameters - the index of the element to be replaced and the new element to replace the existing element.

The System.out.println statement is used to print the list linked list after replacing the element at index 1. As a result, the element at index 1 in the list linked list will be replaced with "Watermelon", as demonstrated by the printed output.

Source Code

import java.util.*;
public class Replace_Position
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();  
		list.add("Apple"); 
		list.add("Mango");     
		list.add("Pineapple");  
		list.add("Cherry");    
		list.add("Guava");
		System.out.println(list);  
		list.set(1, "Watermelon"); 
		System.out.println(list);
	}
}

Output

[Apple, Mango, Pineapple, Cherry, Guava]
[Apple, Watermelon, Pineapple, Cherry, Guava]

Example Programs