Collections

Java ArrayList Iterator example

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

How to get ArrayList Iterator?

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 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, iterator will throw ConcurrentModificationException.

Also see how to iterate ArrayList using various methods example.

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

Join 1000+ fellow learners! Enter your email address below: