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.example.util;

import java.util.LinkedList;

public class LinkedListRemove {
    public static void main(String[] args) {
        LinkedList 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 Saryada

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

Leave a Reply