Iterator objects

Hello,

Regarding the Subsection 8.9.3: Iteration, from the conceptual perspective, it seems that interface could have objects which are created by more sophisticated constructor, which does not exist in the interface. An example is the code given in lecture note for an itertor method implemented in the collection class ArrayList:

public Iterator <E> iterator () {
      return new Iterator () {
            private int i = 0;
            public E next () {
                  return elements [i];
            }
            boolean hasNext () {
                  return i < size ;
            }
       };
 }

Is this constructor implicitly defined for the interface Iterator as special case or there is some general concept behind this?

I do not quite get your question.

The important aspect of an iterator is to iterate through data.
Two important methods shown here are:

  • Querying whether there is more data
  • Getting the next element of our data collection

For array lists, this is quite simple:
Go through the array and return one element after the other.

But one can imagine quite fancy data structures with more complex iterators.
For instance, try to create an iterator for the ordered set of Fibonacci numbers such that:

it = fibonacciIterator();
it.next() == 0
it.next() == 1
it.next() == 1
it.next() == 2
it.next() == 3
it.next() == 5
...

Iterators are a similar concept to the generators you have seen in Programming 1. The only difference is that they are usually linked to a data structure.

1 Like

Basically, Iā€™m wondering, why is it possible for an interface, e.g. Iterator<E> to has a constructor which is used in the above example.

That is a so-called anonymous (inner) class.
You create a class on the fly without a name that has to implement all required methods of the interface.

1 Like