Java ArrayList remove() Method Example

ArrayList remove() removes the first occurrence of the specified element from this list if it is present. If the list does not contain the element, the list remains unchanged.

Java ArrayList remove(Object o) Method Example

Java program to remove an object from an ArrayList using remove() method:
import java.util.ArrayList;

import java.util.Arrays;

public class ArrayListExample 

{

    public static void main(String[] args) throws CloneNotSupportedException 

    {

        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));

         

        System.out.println(alphabets);

         

        alphabets.remove("C");          //Element is present

         

        System.out.println(alphabets);

         

        alphabets.remove("Z");          //Element is NOT present

         

        System.out.println(alphabets);

    }

}
Program output.
Console
[A, B, C, D]

[A, B, D]

[A, B, D]

Java ArrayList remove(int index) Method Example

Java program to remove an object by its index position from an ArrayList using remove() method.
import java.util.ArrayList;

import java.util.Arrays;

public class ArrayListExample {
    public static void main(String[] args) throws CloneNotSupportedException {

        ArrayList < String > alphabets = new ArrayList < > (Arrays.asList("A", "B", "C", "D"));

        System.out.println(alphabets);

        alphabets.remove(2); //Index in range - removes 'C'
        System.out.println(alphabets);
        alphabets.remove(10); //Index out of range - exception
    }
}
Program output.
[A, B, C, D]

[A, B, D]

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 4

    at java.util.ArrayList.rangeCheck(ArrayList.java:653)

    at java.util.ArrayList.remove(ArrayList.java:492)

    at com.howtodoinjava.example.ArrayListExample.main(ArrayListExample.java:1

Reference

Java ArrayList Source Code Examples


Comments