In this tutorial we will learn how to add a new element at specific index in LinkedList. We will be using add(int index, Element E) method of LinkedList class to perform this operation.
More about this method from javadoc:
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).
Example
In this example we have a LinkedList of Strings and we are adding an element to its 5th position(4th index) using add() method. The complete code is as follows:
import java.util.LinkedList;
import java.util.Iterator;
public class AddElement {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Add elements to LinkedList
linkedlist.add("Delhi");
linkedlist.add("Agra");
linkedlist.add("Mysore");
linkedlist.add("Chennai");
linkedlist.add("Pune");
// Adding new Element at 5th Position
linkedlist.add(4, "NEW ELEMENT");
// Iterating the list in forward direction
System.out.println("LinkedList elements After Addition:");
Iterator it= linkedlist.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Output:
LinkedList elements After Addition: Delhi Agra Mysore Chennai NEW ELEMENT Pune
Leave a Reply