Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Why this method of iterating thru a list result in an infinite loop?

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code. Why is the first while loop result in an infinite loop? It seems that list.iterator().hashCode() gives me a different code/iterator every single time. Does anyone know why?

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does that because that's the correct behaviour. iterator() is supposed to return an Iterator over all the elements in the list. You shouldn't have to worry about what other Iterators already exist and what state they are in. So it will always return one initialised at the beginning.
 
Ranch Hand
Posts: 61
1
IntelliJ IDE Tomcat Server Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Kelly Wood wrote:Consider the following code. Why is the first while loop result in an infinite loop? It seems that list.iterator().hashCode() gives me a different code/iterator every single time. Does anyone know why?



When you first execute the list.iterator().hasNext(), it creates the iterator and checks if it has at least 1 element left. Since this is the first call for this iterator, he has one more element so this evaluates to true. And it goes again. But the thing is that instead of checking hasNext() on the same iterator, it creates a new iterator, and this one of course has one more element. And it goes like that till the end of time ... and beyond.

This is equivalent to:
 
    Bookmark Topic Watch Topic
  • New Topic