Skip to content

Java LinkedList Replace Element Example

This example shows how to replace an element in the LinkedList in Java. This example also shows how to replace an element at the specified index using the LinkedList set method.

How to replace an element of the LinkedList in Java?

The set method of the LinkedList class is used to replace an element at the specified index of the LinkedList object.

The set method replaces the element located at the specified index with the given element. It returns the old element that was located at the specified index before the replacement.

Example

Output

The LinkedList set method throws IndexOutOfBoundsException exception if the specified index is out of the range of the list object. That is if the specified index is less than 0 or it is greater than or equal to the linked list size.

In order to avoid this exception, always make sure to check the size of the LinkedList object before calling this method.

Note: The LinkedList element starts from index 0 and goes up to the list size – 1 index. In other words, the first element of the LinkedList object is located at index 0 and the last element of the linked list object is located at the list size – 1 index.

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

Leave a Reply

Your email address will not be published.