In this article we will discuss how to add elements at a particular index or position in a LinkedList in Java.

add() member function of LinkedList always appends the element at the end of LinkedList. Now suppose we don’t want to add element at the end of Linked List instead of it we want to add element somewhere in middle of LinkedList,

To add the element at the middle of LinkedList we will use an overloaded version of add() function i.e.

void add(int index, E element)

It will insert the given element at the specified index (position) in this list.

Lets see how to do this,

package com.thispointer.java.collections.linkedlist;

import java.util.LinkedList;
import java.util.List;

public class Example2 {

	public static void main(String[] args) {

		// Create a LinkedList of String objects
		List<String> listOfStr = new LinkedList<>();
		
		// Add Elements at the end of LinkedList
		listOfStr.add("333");
		listOfStr.add("666");
		listOfStr.add("999");
		
		//Add element at 3rd position in List
		listOfStr.add(3, "777");

		//Display the List
		System.out.println(listOfStr);

		//Add element at 1st position in List
		listOfStr.add(3, "000");

		//Display the List
		System.out.println(listOfStr);

	}
}

 

OUTPUT

[333, 666, 999, 777]
[333, 666, 999, 000, 777]

 

In above example we inserted 2 elements in a LinkedList at 3rd and 1st position respectively.

Join a list of 2000+ Programmers for latest Tips & Tutorials