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


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.


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.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *