How to Insert an Element into LinkedList in Java


In this example, let us see how to insert an element to LinkedList at specified index with add method in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class LinkedListInsertElement {

	public static void main(String[] args) {
		
		//create LinkedList.
		LinkedList linkedList = new LinkedList();
		
		linkedList.add("1");
		linkedList.add("2");
		linkedList.add("4");
		linkedList.add("5");
		
		System.out.println("Before inserting element LinkedList is : " + linkedList);
		
		/*
		 To insert an element into LinkedList object, use
         	 add(int index , Object element) method.
		*/
		linkedList.add(2, "3");
		System.out.println("After inserting 2.5, LinkedList is : " + linkedList);
	}

}

Output:

Before inserting element LinkedList is : [1, 2, 4, 5]
After inserting 2.5, LinkedList is : [1, 2, 3, 4, 5]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments