How do I insert an item into LinkedList?

Category: java.util, viewed: 375 time(s).

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<String>();
        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
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats