What is the LinkedList.set method in Java?

LinkedList

Linked List is a collection of linear data elements. Each element (or node) contains a data part and a reference part.

The data part has the value and the reference part has the address link to the next element.

The elements are not indexed, so random access like in an array is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is the doubly-linked listEach node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package.

What is the set method of LinkedList class?

The set method can be used to set/replace the element at the specified index with the specified element in the LinkedList.

Syntax

public E set(int index, E element)

This method takes the index and the element to be replaced as an argument.

This method returns the previous element at the specified index of the list.

The IndexOutOfBoundsException exception is thrown if the index is negative or greater than the list size (index < 0 || index >= size()).

Code

The code below demonstrates how to use the set method:

import java.util.LinkedList;
class LinkedListSetExample {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
System.out.println("The old element at index 0 " + list.set(0, "10"));
System.out.println("The list is " + list);
}
}

Explanation

In the above code:

  • In line number 1, we import the LinkedList class.

  • In line number 4, we create a LinkedList objects with the name list.

  • From line number 5 to 7, we use the add method of the list object to add three elements ("1","2","3") to the list.

  • In line number 10, we use the set method of the list object to replace the element at index 0 with the element "10". The set method replaces the first element with "10" and returns the old element "1".

Free Resources