Tony Marshle
Tony Marshle

Reputation: 127

Java iterator stuff

public class Show {
    public static ArrayList Ara = new ArrayList();
    public static Iterator snake;

    public static void kai(){
        Ara.add(1);
        Ara.add(2);
        Ara.add(5);
        Ara.add(7);
        Ara.add(10);
        Ara.add(13);        
        snake = Ara.iterator();
        while(snake.hasNext()){
            System.out.println(snake.next());
            if(snake.next()==7)break;
        }
    }       

    public static void main(String[] args){
        kai();
    }
}

At execution, 1, 5, 10 consecutively prints out. How do I explain this? I expected 1, 2, 5 would print out instead.

Upvotes: 1

Views: 150

Answers (2)

You are calling Iterator.next() multiple times (twice) inside the while loop ... that is the reason that explains the behav...

Your list has this elements: 1,2,5,7,10 and 13 and this line System.out.println(snake.next()); discards and prints the element 1,5,10

BTW the list is raw in your example, so I can imagine, the condition snake.nect()==7 is never met and therefore not breaking the loop

I didn't try to hard to fix it, in fact code is not compiling because of an Incompatible operand types Object and int if you code properly the collection (not using raw) then you will need to do something like

 if (((Integer) snake.next()).intValue() == 7)

Upvotes: 1

Jose da Silva Gomes
Jose da Silva Gomes

Reputation: 3974

You should change the code like the following:

public static void kai(){
    Ara.add(1);
    Ara.add(2);
    Ara.add(5);
    Ara.add(7);
    Ara.add(10);
    Ara.add(13);        
    snake = Ara.iterator();
    while(snake.hasNext()){
        int value = (int) snake.next();
        System.out.println(value );
        if(value ==7)break;
    }
}    

That way you only call iterator.next() one time inside the while loop.

Upvotes: 2

Related Questions