Java – Add Element At Specific Index In LinkedList
Chapter:
Data Structures
Last Updated:
13-08-2016 13:48:28 UTC
Program:
/* ............... START ............... */
import java.util.LinkedList;
import java.util.Iterator;
public class JavaLinkedListSpecificIndex {
public static void main(String[] args) {
// create a LinkedList
LinkedList<String> list = new LinkedList<String>();
// Adding elements to the LinkedList
list.add("Harry");
list.add("James");
list.add("Tom");
list.add("Steve");
// Adding new Element at 5th Position
list.add(4, "New Element");
// Iterating the list in forward direction
System.out.println("LinkedList elements After Addition:");
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
/* ............... END ............... */
Output
LinkedList elements After Addition:
Harry
James
Tom
Steve
New Element
Notes:
-
public void add(int index, E element): Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Tags
Add Element At Specific Index In LinkedList, Java, Data Structures