How to replace element in LinkedList

This example shows how to replace an element of a Java LinkedList . This example also shows how to
how to change values in a linked list using LinkedList set() method .

Replace an Element of LinkedList Java example

We can replace element in LinkedList using LinkedList Set() method. This method replaces the element at the specified position in this LinkedList with the specified element. Let’s see Java LinkedList Set() method Example.

import java.util.LinkedList;

public class ReplaceElement {

public static void main(String[] args) {

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

linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println("Before Replace Element Linklist is = "+linkedList);

/*
* Replaces the element at the specified position in
* this list with the specified element.
*/

linkedList.set(2,"chandigarh");

System.out.println("After Replace Element Linklist is = "+linkedList);

}

}

Output:

Before Replace Element Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

After Replace Element Linklist is = [Mumbai, Delhi, chandigarh, Gao, Patna]

In this example we have seen how to how to update values in a linked list using LinkedList set() method example .This article is one example of Java Collection Framework .

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 50 = 55