I have implemented a simple iterator. Just want to check if I have missed anything.
interface iterator<E>
{
boolean hasNext();
E next();
}
class Iterator<E> implements iterator
{
E[] arr;
int curPos = 0;
@Override
public boolean hasNext()
{
if (curPos >= arr.length || arr[curPos] == null)
{
return false;
}
else
{
return true;
}
}
@Override
public E next()
{
if(hasNext())
{
E res = arr[curPos];
curPos++;
return arr[curPos+1];
}
else
{
throw new runtimeException("No next element available !");
}
}
}
Questions:
- Why should I not use
Object
instead ofE
/template everywhere ? - How do I make an iterator for a binary tree.
I assume apart from the above, I would have to implement a traversal algorithm and try to find if the next "traversal" successor exist?