1. Introduction
The LinkedList class in Java provides the set(int index, E element) method which allows us to replace an element at a specific position in the list with the specified element. This post illustrates how to use this method to change elements in a LinkedList.
2. Program Steps
1. Create and initialize a LinkedList.
2. Print the original LinkedList.
3. Use the set(int index, E element) method to replace an element at a specific index.
4. Print the updated LinkedList.
3. Code Program
import java.util.LinkedList;
public class LinkedListSetElementExample {
public static void main(String[] args) {
// Step 1: Create and initialize a LinkedList
LinkedList<String> animals = new LinkedList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Step 2: Print the original LinkedList
System.out.println("Original LinkedList: " + animals);
// Step 3: Use the set(int index, E element) method to replace an element at a specific index
animals.set(1, "Tiger"); // Replacing "Cat" with "Tiger" at index 1
// Step 4: Print the updated LinkedList
System.out.println("Updated LinkedList: " + animals);
}
}
Output:
Original LinkedList: [Dog, Cat, Horse] Updated LinkedList: [Dog, Tiger, Horse]
4. Step By Step Explanation
Step 1: We create and initialize a LinkedList named animals with the elements "Dog", "Cat", and "Horse".
Step 2: We print the original LinkedList to the console.
Step 3: We use the set(int index, E element) method of the LinkedList class to replace the element at index 1 ("Cat") with "Tiger".
Step 4: We print the updated LinkedList to the console to show the change. The output shows that "Cat" has been successfully replaced with "Tiger".
In summary, the set method is a convenient way to modify elements at a specific position in a LinkedList in Java.