Remove an Element from ArrayList in JavaArrayList is similar to the array whose size can be modified. The ArrayList class is available in the Java.util package and extends the List interface. Adding and removing an element from the ArrayList is very easy by using its built-in methods add() and remove(). However, there is more than one way of removing an element from the ArrayList that are as follows:
![]() All these three ways are best in their own, and can be used in some different scenario. Let's understand all these three ways, one by one. ArrayList.remove() MethodUsing the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj). The remove(int index) method accepts the index of the object to be removed, and the remove(Object obj) method accepts the object to be removed. Let's take an example to understand how the remove() method is used. RemoveMethod.java Output: ![]() Let's take another example to understand how the remove() method is used to remove the specified element from the ArrayList. RemoveElementMethod.java Output: ![]() Iterator.remove() MethodThe Iterator.remove() method is another way of removing an element from an ArrayList. It is not so helpful in case when iterating over elements. When we use the remove() method while iterating the elements, it throws the ConcurrentModificationException. The Iterator class removes elements properly while iterating the ArrayList. Let's take an example to understand how the Iterator.remove() method is used. IteratorRemoveMethod.java Output: ![]() ArrayList.removeIf() MethodIf we want to remove an element from the ArrayList which satisfy the predicate filter, the removeIf() method is best suited for this case. We pass the predicate filter to that method as an argument. Let's take an example to understand how the removeIf() method is used. RemoveIfMethod.java Output: ![]() All of the above-discussed methods are used for different scenarios. Using ArrayList.remove() method is the fastest way for removing an element from the ArrayList. |