How to Remove Element From ArrayList in Java

If you need to remove or delete an element from ArrayList in Java, you have 3 options.

  1. Using the remove() method of the ArrayList class to remove element.
  2. Using the remove() method of the iterator returned by ArrayList.
  3. Using the removeIf() method Java 8 onwards.

Removing element using ArrayList’s remove method

There are two variants of the remove() method in the ArrayList class-

  • remove(int index)– This method removes the element at the specified index in this list.
  • boolean remove(Object o)– This method removes the first occurrence of the specified element from this list, if it is present.

Example code

Here is an example to remove element from ArrayList in Java by passing the element itself (using remove(Object o) method).

Output

Removing element using iterator’s remove method

If you want to remove an element from ArrayList while iterating the ArrayList then you should use remove() method of the Iterator itself. It is required because it is not permitted to structurally modify (add or remove elements) ArrayList at any time after the iterator is created except through the iterator’s own remove method not doing so will result in ConcurrentModificationException being thrown.

Let us see it by an example, here element is removed while iterating the List using remove method of the ArrayList class.

Output

Here is the changed code where iterator’s remove method is used to remove element from ArrayList.

Output

As you can see ConcurrentModificationException is not thrown now.

Removing element using removeIf method

Java 8 onwards you can also use removeIf() method to remove element from ArrayList which takes a predicate as an argument and removes all elements that satisfy the given predicate.

Autoboxing issue with remove() method

Since remove() method in ArrayList is overloaded having variants where you can either pass index or object to remove. These overloaded methods may cause problem if element is wrapped to its corresponding wrapper class because of autoboxing.

Let’s try to clarify it with an example where you have an ArrayList of Integers.

Here you are passing Integer object 6 to be removed from the ArrayList, but the remove() method with int parameter as argument will be used. No autoboxing will happen in this case and you will get an error.

If there is such ambiguity you should pass object itself for removal.

That’s all for the topic How to Remove Element From ArrayList in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.