Iterators Flashcards
What is an Iterator?
Iterators are (usually) a special class/object that allows the user to easily traverse a data structure.
What kind of methods does an Iterator have?
Iterators usually have methods to get the current item, go to the next item, or go to the previous item.
How is an Iterator used?
The data structure itself implements the iterator (usually as an inner class or a private class).
What needs to be done to have an Iterator in your class?
The class itself would implement the Iterable interface (in the java.lang package), which has just one method: iterator(). This method returns an instance of the iterator for that data structure.
What methods does the Iterator interface have?
The Iterator interface in Java has three methods:
hasNext(), next(), and remove().
What does the hasNext() method do?
hasNext() tells you whether calling next() will return the
next item in the data structure (i.e. if there is at least one
more item).
What does the next() method do?
next() returns the next item in the data structure.
What does the remove() method do?
remove() removes the most-recently returned item.