Replace element with a new value in LinkedList

In the previous post, we have seen how to iterate over a list in reverse order. In this post, we will learn how to replace element with a new value in LinkedList.

We use a method ‘Set’ which accepts arguments as index and element value which will be replaced.

Syntax:

public E set(int index, E element)

Example:

import java.util.LinkedList;

public class LinkedListEx {

	public static void main(String[] args) {
		LinkedList<String> fruits = new LinkedList<String>();
		fruits.add("Orange");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Grapes");
		fruits.add("Banana");
	
		System.out.println("List before replacement : "+fruits);
		
		fruits.set(0, "Papaya");
		System.out.println("List after replacement : "+fruits);
	}
}

Output:

List before replacement :[Orange, Mango, Apple, Grapes, Banana]
List after replacement :[Papaya, Mango, Apple, Grapes, Banana]


Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...