What is the Difference Between remove Methods of Collection and Iterator in Java ?

In Collection interface remove(Object o) method is used to remove objects from a Collection.

List interface also provides remove(int index) method to remove an object at a specific index.

These methods are used to remove an entry from Collection, while no thread is iterating over it.

When we are iterating over a Collection, then we have to remove() method of Iterator. This method removes current element from Iterator’s point of view. If we use remove(0 method of Collection or List, then we will get ConcurrentModificationException.

Therefore, it is recommended to use remove() method of Iterator during the traversal of a Collection by an Iterator.



You May Interest

Java How To Find The Average Of 10 Numbers Using A While Loop

Why Collection Interface Doesn’t Extend Cloneable and Serializabl ...

How Can You Determine If Your Program Has a Deadlock in Java ?

What is the Difference Between Fail-fast and Fail-safe Iterator i ...

How Can We Reference an Unreferenced Object Again in Java ?