LinkedList set() Method in Java (original) (raw)

Last Updated : 31 Mar, 2023

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.

Syntax:

LinkedList.set(int index, Object element)

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

Return Value: The method returns the previous value from the linked list that is replaced with the new value. Below program illustrates the Java.util.LinkedList.set() method:

Example 1:

Java `

// Java code to illustrate set() Method

// Importing required libraries import java.io.*; import java.util.LinkedList;

// Class public class LinkedListDemo {

// Main driver method
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
    list.add("Geeks");
    list.add("for");
    list.add("Geeks");
    list.add("10");
    list.add("20");

    // 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);
}

}

`

Output

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]

The set(int index, E element) method in Java is used to set the element of a LinkedList at the specified index with a new element. This method replaces the existing element at the specified index with the new element.

Example 2: Here is an example of how to use the set() method

Java `

import java.util.LinkedList;

public class LinkedListExample

public static void main(String[] args) { // Create a LinkedList of Strings LinkedList list = new LinkedList(); list.add("apple"); list.add("banana"); list.add("cherry"); list.add("date"); list.add("elderberry");

// Replace an element in the LinkedList
list.set(2, "grape");

// Print the updated LinkedList
System.out.println("LinkedList after replacement: "
                   + list);

} }

`

Output

LinkedList after replacement: [apple, banana, grape, date, elderberry]

In this example, we first create a LinkedList of Strings named list with five elements. We then use the set() method to replace the element at index 2 with the String "grape". The index of the elements in a LinkedList starts from 0.