java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.util;

import java.util.LinkedList;

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