Click here to Skip to main content
15,936,983 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I recently learned about iterating a collection in Java using the Iterator. I thought I completely understood the concept until I tested my understanding. It turns out I didn't get it right.

Can someone please explain why the 1st code runs but the 2nd code results in an infinite while loop.

ArrayList<Integer> al = new ArrayList<>(Arrays.asList(1,2,3));
Iterator<Integer> iterator = al.iterator();
    int i =;
}//This works

ArrayList<Integer> al = new ArrayList<>(Arrays.asList(1,2,3));
while (al.iterator().hasNext()) {
}//This doesn't work

As you can tell, I'm totally new to java and programming. Any help will be greatly appreciated.

What I have tried:

I tried searching this on google but couldn't find a solution specific to my problem, I guess I'm the only dumbest person around here.
Updated 3-May-22 5:10am

Because each time you do this:
You create a new iterator over the collection, which starts at the first element.

The first example saves the iterator so it uses the same one through the whole sequence, but the second uses a new instance each time it goes round the loop.

Java Iterator[^]
Share this answer
Thank you for your reply. So we need to create a reference to the iterator that is returned by
, hmmm, interesting. I think now I understand why my code was not working. It was using a new iterator object that is returned by al.iterator each time the code ran. That was the reason it never get beyond the first element in the list. Thanks again. :-) :-)
Share this answer
Richard Deeming 3-May-22 12:01pm    
If you want to reply to a solution, click the "Have a Question or Comment?" button under the solution and post a comment. Do not post your comment as another "solution".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900