LinkedList
Insert element at specific index in LinkedList example
With this example we are going to demonstrate how to insert an element at a specific index in a LinkedList. In short, to insert an element at a specific index in a LinkedList you should:
- Create a LinkedList.
- Populate the list with elements, with
add(E e)API method. - Invoke a
dd(int index , Object element)API method of LinkedList. It inserts the specified element at the specified index in the list, while current and subsequent elements are shifted to the right.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.util.LinkedList;
public class InsertElementAtIndexLinkedList {
public static void main(String[] args) {
// Create a LinkedList and populate it with elements
LinkedList linkedList = new LinkedList();
linkedList.add("element_1");
linkedList.add("element_2");
linkedList.add("element_3");
linkedList.add("element_4");
linkedList.add("element_5");
System.out.println("LinkedList contains : " + linkedList);
/*
* void add(int index , Object element) method inserts the specified element
* at the specified index in the LinkedList. Current and subsequent elements
* are shifted to the right
*/
linkedList.add(3, "element_6");
System.out.println("After inserting element_6 at index 3, LinkedList contains : " + linkedList);
}
}
Output:
LinkedList contains : [element_1, element_2, element_3, element_4, element_5]
After inserting element_6 at index 3, LinkedList contains : [element_1, element_2, element_3, element_6, element_4, element_5]
This was an example of how to insert an element at a specific index in a LinkedList in Java.
