Write a Java program to replace an element in a linked list
The Java code provided demonstrates how to replace an element in a linked list using the set method.
- The code defines a class named Replace_Element with a main method, which serves as the entry point for the Java program.
- Inside the main method, a LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
- Strings such as "Watermelon", "Apple", "Cherry", and "Banana" are added to fru_list using the add method, which appends the elements to the end of the list.
- The System.out.println statements are used to print the initial contents of fru_list before any modifications.
- The fru_list.set(2, "Pineapple") method is called to replace the element at index 2 in fru_list with the string "Pineapple". The set method takes two parameters: the index at which the element needs to be replaced, and the new value to be inserted at that index.
- A System.out.println statement is used to print the message "Replace an Element in a linked list."
- Another System.out.println statement is used to print the contents of fru_list after replacing the element, which will now include "Pineapple" at index 2.
- The output of the program will be the initial contents of fru_list printed on the first line, followed by the message "Replace an Element in a linked list." printed on the second line, and the updated contents of fru_list with "Pineapple" at index 2 printed on the third line.
Source Code
import java.util.LinkedList;
import java.util.Collections;
public class Replace_Element
{
public static void main(String[] args)
{
LinkedList<String> fru_list= new LinkedList<String>();
fru_list.add("Watermelon");
fru_list.add("Apple");
fru_list.add("Cherry");
fru_list.add("Banana");
System.out.println("Given linked list : " + fru_list);
fru_list.set(2, "Pineapple");
System.out.println("Replace an Element in a linked list.");
System.out.println("New linked list: " + fru_list);
}
}
Output
Given linked list : [Watermelon, Apple, Cherry, Banana]
Replace an Element in a linked list.
New linked list: [Watermelon, Apple, Pineapple, Banana]