What is an Iterator ?

What is an Iterator ?

Some points are as follows to define Iterator:

1 The Iterator interface is used to step through the elements of a Collection.
2 Iterators let you process each element of a Collection.
3 Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
4 Iterator is an Interface implemented a different way for every Collection.

It comes inside java.util package. as public interface Iterator and contains three methods:

boolean hasNext(): this method returns true if this Iterator has more element to iterate.

Object next(): return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator

remove(): method remove the last element return by the iterator this method only calls once per call to next().

Read More →