Replace an element of a Java LinkedList

Java 8Object Oriented ProgrammingProgramming

An element in an Java LinkedList can be replaced using the java.util.ArrayList.set() method. This method has two parameters i.e the index at which the LinkedList element is to be replaced and the element that it should be replaced with. ArrayList.set() method returns the element that was at the position specified at the index previously.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Pear");
      l.add("Apple");
      l.add("Mango");
      l.add("Guava");
      l.add("Orange");
      System.out.println("The LinkedList is: " + l);
      l.set(2, "Peach");
      System.out.println("The LinkedList is: " + l);
   }
}

Output

The LinkedList is: [Pear, Apple, Mango, Guava, Orange]
The LinkedList is: [Pear, Apple, Peach, Guava, Orange]

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.set() is used to replace the element “Mango” with “Peach” at index 2. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("Pear");
l.add("Apple");
l.add("Mango");
l.add("Guava");
l.add("Orange");
System.out.println("The LinkedList is: " + l);
l.set(2, "Peach");
System.out.println("The LinkedList is: " + l);
raja
Published on 10-Jan-2019 08:14:57
Advertisements