Tuesday, September 10, 2013

Iterators - Allowing iteration over data structures (in java)

Many times we need to iterate over the data structures. But should we allow our clients to know the internal details of the data-structure like whether it is using array or linked list and then iterate themselves.

Here's where java gives us the power called iterators which allows us to iterate over data structure.

Design Challenge
Consider the stack data structure and we want to support iteration over it on client side.

Step 1 - Make your stack ADT implement Iterable interface.
What is Iterable?
has a method that returns an Iterator.
public interface Iterable <Type>{
  Iterator <Type>l; iterator();
}


What is Iterator?
Has methods hasNext() and next()
public interface Iterator<Type>{
    boolean hasNext();//tells if it has more element
    Type next();      //gives the next element
    void remove();    //use at your own risk
}


What makes a data structures Iterable?
Once the class implements Iterable interface, one can do following
for(String s:stack)
   print (s);//print each string in stack

here the stack is Stack of strings.
Long hand code to do the same(though not needed in newer versions of java)
Iterator <String> i = stack.iterator();
while(i.hasNext())
{
    String s = i.next();
    print s;
}

Now the class becomes.

0 comments:

Post a Comment