Java LinkedList set() Method Tutorial

In this section, we will learn what the LinkedList set() method is and how to use it in Java.

What is Java LinkedList set() Method?

The Java LinkedList set() method is used to set a new element in a specific index to replace the old value that is already there in a LinkedList object.

Java set() Method Syntax:

public E set(int index, E element)

set() Method Parameters:

The method takes two arguments:

  • The first argument is the index number where we want to set the new element.
  • The second argument is the new element we want to replace with the old one in that index.

set() Method Return Value:

The return value of this method is the old value that was replaced as a result of calling the method.

set() Method Exceptions:

IndexOutOfBoundsException: we get this exception if the index number (the first argument) is out of range in the target LinkedList object.

Example: using LinkedList set() method

import java.util.LinkedList;

class Main{

public static void main(String[] args) {

LinkedList<String> list = new LinkedList<>();

list.addFirst(“John”);

list.addFirst(“Omid”);

list.addFirst(“Jack”);

list.addFirst(“Ellen”);

list.addFirst(“Elon”);

list.set(2, “James”);

for (String s: list){

System.out.println(s);

}

}

}

Output:

Elon

Ellen

James

Omid

John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies