Java Utility Library

Java ArrayList - remove() Method



The java.util.ArrayList.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.ArrayList.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 an ArrayList
    ArrayList<String> MyList = new ArrayList<String>();

    //populating ArrayList
    MyList.add("A");
    MyList.add("B");
    MyList.add("C");
    MyList.add("B");
    MyList.add("D");
    
    //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, D]
MyList contains: [A, C, B, D]

❮ Java.util - ArrayList