Wednesday, June 30, 2010

Confusing Stack Iterator.

I was using the Stack<E> class from the Java Collections framework for the first time. I think the Iterator returned by this Collection is confusing. Consider the following code :

import java.util.Iterator;
import java.util.Stack;

public class Main {
   
    public static void main(String[] argv) {
        Stack<String> lStack = new Stack<String>();
        lStack.add("ONE");
        lStack.add("TWO");
        lStack.add("THREE");
       
        Iterator<String> lIterator = lStack.iterator();
        while ( lIterator.hasNext() ) {
            System.out.println( lIterator.next());
        }
     }
}

I was hoping that the output from the above code would be :
THREE
TWO
ONE

But, the output was :
ONE
TWO
THREE

The reason why i expect it to be like the first output shown above is - It is a Stack and a Stack orders elements in a Last In First Out (LIFO) manner. Hence the Iterator returned  from the call lStack.Iterator() should preserve this ordering. Am I missing something obvious ?

No comments:

Post a Comment

Followers

About Me

I'm a software developer with interests in Design Patterns, Distributed programming, Big Data, Machine Learning and anything which excites me. I like to prototype new ideas and always on the lookout for tools which help me get the job done faster. Currently, i'm loving node.js + Mongodb.