How do I remove an item from LinkedList?

This program shows you how to use the remove(int index) method of LinkedList class to remove an item at specified index from linked list object.

package org.kodejava.util;

import java.util.LinkedList;

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

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

        // Remove Carol from the linked list.
        names.remove(2);

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

The result of the program above are:

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.