LinkedList set() Method in Java

The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.


LinkedList.set(int index, Object element)

Parameters: This function accepts two parameters as shown in the above syntax and described below.

  • index: This is of integer type and refers to the position of the element that is to be replaced from the linked list.
  • element: It is the new element by which the existing element will be replaced and is of the same object type as the linked list.

Return Value: The method returns the previous value from the linked list that is replaced with the new value.

Below program illustrate the Java.util.LinkedList.set() method:





// Java code to illustrate set()
import java.util.LinkedList;
public class LinkedListDemo {
    public static void main(String args[])
        // Creating an empty LinkedList
        LinkedList<String> list = new LinkedList<String>();
        // Use add() method to add elements in the list
        // Displaying the linkedlist
        System.out.println("LinkedList:" + list);
        // Using set() method to replace Geeks with GFG
        System.out.println("The Object that is replaced is: " + list.set(2, "GFG"));
        // Using set() method to replace 20 with 50
        System.out.println("The Object that is replaced is: " + list.set(4, "50"));
        // Displaying the modified linkedlist
        System.out.println("The new LinkedList is:" + list);



LinkedList:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new LinkedList is:[Geeks, for, GFG, 10, 50]

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.