How to replace element in LinkedList

 We can replace any specific index element by other element using set(int index,element) method.

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]

Leave a Reply

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

84 − = 80