How do I insert an item into LinkedList?

To insert an item at any position into a linked list object we can use the add(int index, Object o) method. This method takes the index to where the new object to be inserted and the object to be inserted itself.

package org.kodejava.example.util;

import java.util.LinkedList;

public class LinkedListAddDemo {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Mallory");

        System.out.println("Original values are:");
        System.out.println("====================");
        for (String name : names) {
            System.out.println("Name = " + name);
        }

        // Add a new item to the list at index number 2. Because
        // a list are 0 based index Carol will be inserted after
        // Bob.
        names.add(2, "Carol");

        System.out.println("New values are:");
        System.out.println("====================");
        for (String name : names) {
            System.out.println("Name = " + name);
        }
    }
}

The result of our program are:

Original values are:
====================
Name = Alice
Name = Bob
Name = Mallory
New values are:
====================
Name = Alice
Name = Bob
Name = Carol
Name = Mallory

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply