Java Utility Library

Java LinkedList - remove() Method



The java.util.LinkedList.remove() method is used to remove the first occurrence of the specified element from this list, if it is present. It shifts any subsequent elements to the left by subtracting one from their indices. Every removal of element results into reducing the list size by one unless the list is empty.

Syntax

public boolean remove(Object obj)

Parameters

obj Specify the element which need to be removed from this list, if present.

Return Value

Returns true if this list contained the specified element.

Exception

NA.

Example:

In the example below, the java.util.LinkedList.remove() method is used to remove the first occurrence of "B" from the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<String> MyList = new LinkedList<String>();

    //populating linkedlist
    MyList.add("A");
    MyList.add("B");
    MyList.add("C");
    MyList.add("B");
    MyList.add("E");

    //printing linkedlist
    System.out.println("MyList contains: " + MyList);

    //remove the first occurrence of "B"
    MyList.remove("B");

    //printing linkedlist
    System.out.println("MyList contains: " + MyList);
  }
}

The output of the above code will be:

MyList contains: [A, B, C, B, E]
MyList contains: [A, C, B, E]

❮ Java.util - LinkedList