Skip to content

Java ArrayList Iterator example

Java ArrayList Iterator example shows how to get Iterator over ArrayList elements in Java. The example also shows how to iterate ArrayList using hasNext and next methods of Iterator.

How to get ArrayList Iterator?

The ArrayList class implements Iterable interface hence it provides iterator method which can be used to get the Iterator object over its elements.

This method returns an Iterator object over ArrayList elements of type T.

How to Iterate ArrayList using Iterator object?

Once we get the Iterator object from the ArrayList, we can use hasNext and next methods of Iterator to iterate through the ArrayList.

This method returns true if the Iterator has more elements.

This method returns the next element in the iteration.

Note: next() method may throw NoSuchElementException if there are no more elements. Always check if there are more elements to iterate using hasNext() method before making call to the  next() method to avoid this exception.

ArrayList Iterator example

Output

How to remove elements while iterating through the ArrayList?

You can call remove method of Iterator class to remove elements from the ArrayList.

This method removes the last element returned by the Iterator from the underlying collection.

Note: This method must be called once per next method call. It may throw IllegalStateException if remove method is already called after the last call to the next method or next method is not called at all. It may also throw UnsupportedOperationException if remove operation is not supported by the underlying collection.

Output

Note: The iterator object returned by the iterator method of the ArrayList class is fail-fast. It means that if the original ArrayList is structurally modified after getting the Iterator from it in any way except for the Iterator’s own methods, the iterator will throw ConcurrentModificationException.

Also, see the how to iterate ArrayList using various methods example.

This example is a part of the Java ArrayList tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.