Remove elements from ArrayList and CopyOnWriteArrayList

ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.

The CopyOnArrayList has remove() method used to remove the element in the list.

1). public E remove(int index)

The remove(int index) method of CopyOnArrayList in Java is used to remove the element at the specified position in the list.

This method throws ArrayIndexOutOfBounds exception if the specified index is out of range i.e index is less than 0 or greater than or equal to the size of the list.

2). public boolean remove(Object o)

The remove(Object o) method of CopyOnArrayList in Java is used to remove the element if it is present in the list.

import java.util.*; public class CopyOnWriteArrayList1 { public static void main(String[] args) { CopyOnWriteArrayList<String> fruitsList = new CopyOnWriteArrayList<String>(); fruitsList.add("apple"); fruitsList.add("mango"); fruitsList.add("kiwi"); // print fruitsList System.out.println("CopyOnWriteArrayList of fruitsList is : " + fruitsList); fruitsList.remove(0); System.out.println(fruitsList); } }

Post/Questions related to How to Read the file from resources folder in Java

Can we remove elements from ArrayList while iterating?
Can we remove elements from ArrayList while iterating?
How do you remove the last element of an ArrayList?
Can we modify ArrayList while iterating?
Yes, we can do that. we have to use list iterator for that.
Can we modify ArrayList while iterating?
ArrayList add/replace the element at the specified index in Java
How do I stop ConcurrentModificationException?
How we prevent java.util.ConcurrentModificationException while dealing with ArrayList?

In this article, we have seen How to Remove elements from ArrayList and CopyOnWriteArrayList.