Iterator Interface

Package: java.util

An iterator is a special type of object whose sole purpose in life is to let you step through the elements of a collection. If you want to build a class that can be processed by the Java enhanced for statement (also known as “foreach”), the class must implement the Iterator class and provide an iterator method, which in turn must return an object that implements the Iterator class. This class must implement each of the three methods listed in the following table.

Methods

Method

Explanation

hasNext()

Returns true if the collection has at least one element that hasn’t yet been retrieved.

next()

Returns the next element in the collection.

remove()

Removes the most recently retrieved element.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.