Java LinkedList - set() Method
The java.util.LinkedList.set() method is used to replace the element at the specified position in the list with the specified element.
Syntax
public E set(int index, E element)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index number of the element to replace. |
element |
Specify the element which need to store at the specified position. |
Return Value
Returns the replaced element (previous element) of the list.
Exception
Throws IndexOutOfBoundsException, if the index is out of range (index < 0 || index >= size()).
Example:
In the example below, the java.util.LinkedList.set() method is used to set the element at the specified position in given list.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a linkedlist LinkedList<Integer> MyList = new LinkedList<Integer>(); //populating linkedlist MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); //printing linkedlist System.out.println("MyList contains: "+ MyList); //modify element at index=2 MyList.set(2, 100); //printing linkedlist System.out.println("MyList contains: "+ MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40] MyList contains: [10, 20, 100, 40]
❮ Java.util - LinkedList