Java ArrayList.remove()

The ArrayLis.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.

1. ArrayList.remove() API

The remove() method is overloaded and comes in two forms:

  • boolean remove(Object o) – removes the first occurrence of the specified element from the list. Returns true is any element was removed from the list, else false.
  • Object remove(int index) – removes the element at the specified position in this list. Shifts any subsequent elements to the left. Returns the removed element from the list. Throws IndexOutOfBoundsException if the argument index is invalid.

2. ArrayList remove() Example

2.1. Remove Single Element from the List

Java program to remove an object from an ArrayList using remove() method. In the following example, we invoke the remove() method two times.

  • If the element is found in the list, then the first occurrence of the item is removed from the list.
  • Nothing happens if the element is NOT found in the list, and the list remains unchanged.
ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));  

alphabets.remove("C");   //[A, B, D]

alphabets.remove("Z");  //[A, B, D]

2.2. Remove All Occurrences of Element

We cannot directly remove all occurrences of any element from the list using remove() method. We can use removeAll() method for this purpose.

Java program to remove all the occurrences of an object from the ArrayList.

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

alphabets.removeAll(Collections.singleton("A"));   //[B, D]

3. Remove Element by Index

While removing an element using the index, we must be very careful about the list size and index argument. Java program to remove an object by its index position from an ArrayList using remove() method.

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

alphabets.remove(2);  //Index in range - removes 'C'

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:18)

That’s all for the ArrayList remove() method in Java.

Happy Learning !!

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.