Please explain to me why when I work with the iterator and forget to initialize the iterator itself, will this cycle continue indefinitely?

//этот работает верно Iterator<Object> iterator2 = set.iterator(); while(iterator.hasNext()) set2.add(iterator.next()); //а вот этот уже начнет разгонять мой процессор до сверхскоростей и все бестолку while(set.iterator().hasNext()) set2.add(set.iterator().next()); 
  • one
    because each .iterator () call gets a new instance of the iterator? - etki

1 answer 1

set.iterator() always creates a new iterator; in the first part of your code, you create it only once:

 Iterator<Object> iterator2 = set.iterator(); 

and so in the subsequent loop it finally runs out, iterator.hasNext() return false and the loop will end,

but in the second part you create it in a loop over and over again :

 while(set.iterator().hasNext()) 

and since it is always fresh , the .hasNext() method again and again returns true and therefore the cycle continues again and again - to infinity.