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 names = new LinkedList();
        names.add("Alice");
        names.add("Bob");
        names.add("Mallory");

        System.out.println("Orignal 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:

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

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply