1
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.

4
  • 1
    you r calling .next multiple times (twice) Commented Nov 13, 2016 at 14:26
  • Please change your title to something more descriptive. Commented Nov 13, 2016 at 14:27
  • snake.next() advances the iterator to the next element. Commented Nov 13, 2016 at 14:27
  • Try assigning snake.next() to a separate variable like int i = snake.next(); Commented Nov 13, 2016 at 14:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

ok, but that doesn't explain why did 10 print out, right? I do understand why 1 prints out, 2 is skipped, and 5 prints out. But then the call to snake.next() would return a 7, and the loop execution should stop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.