In this example, we’ll see how to replace a LinkedList element at specified index with set method of LinkedList class in Java.
Source Code
package com.beginner.examples;
import java.util.LinkedList;
public class LinkedListReplaceElement {
public static void main(String[] args) {
//create LinkedList.
LinkedList linkedList = new LinkedList();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
/*
* To replace an element of LinkedList at specified index, use
* Object set(int index, Object element) method.
*/
linkedList.set(3, "Replaced");
System.out.println("After replacing D, LinkedList is : " + linkedList);
}
}
Output:
After replacing D, LinkedList is : [A, B, C, Replaced]
References
Imported packages in Java documentation: