ArrayList: Iteration
Explore various techniques for iterating over ArrayLists in Java, including traditional for loops, enhanced for loops, and the Iterator interface methods like hasNext, next, remove, and forEachRemaining. Understand how to avoid ConcurrentModificationException by using the Iterator's remove method when modifying collections during iteration.
We'll cover the following...
Iterating an ArrayList
Below are the different methods to iterate over an ArrayList.
Using for loop
An ArrayList can be iterated easily using a simple for loop or an enhanced for loop as shown below.
Using Iterator
The iterator() method in ArrayList returns an Iterator type object. The Iterator interface declares the below methods that help with iterating an ArrayList.
-
hasNext()— This method returnstrueif there are more elements in the list; otherwise, it returnsfalse. -
next()— This method returns the next element in the list. Before callingnext(), we should always callhasNext()to verify that there is an element; otherwise,NoSuchElementExceptionwill be thrown. -
remove()— This method removes the last element returned by the iterator. It can be called only once per call to thenext(). -
forEachRemaining(Consumer<? super E> action)— This method was introduced in Java 8. It performs the given action for each remaining element until all elements have been processed or the action throws an exception. This method’s benefit is that we do not need to check if there is a next element every time.
To understand the working of the
forEachRemaining()method, you should be familiar with basic concepts of functional programming that were introduced in Java 8.
Below is an example of iterating an ArrayList using the iterator.
If we try to directly remove an element while iterating an ArrayList using an iterator is created, then ConcurrentModificationException will also be thrown. We should always use the remove() method in the iterator to remove an element from the ArrayList.
The below program will fail because we are trying to delete the element from the list directly.
The code shown below is the correct way to delete an element from the list.
If an element is added to the ArrayList after the iterator is created then also ConcurrentModificationException will be thrown.