Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Infinte iteration in a list

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a code bit (source :- me )



When i run this code my iterator iterates infinitely . I cant understand why this is happening as Arrays.asList(arrayname) returns a list of finite size so when we iterate on that list there should be four iterations but my output is iterating in an infinite loop . Can anyone explain .
 
ankur trapasiya
Ranch Hand
Posts: 160
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here in this code you are not calling it.next()... that's why it is causing infinite loop


the main purpose of next method is to return the current value in the collection and move the internal pointer to the next element in the collection.. Here you are not calling next() that's why iteration never moves to the next element and it.hasNext() always returns true..
Therefore loop never ends....

i hope you got it
 
Sumit Khurana
Ranch Hand
Posts: 68
Chrome Java MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the main purpose of next method is to return the current value in the collection and move the internal pointer to the next element in the collection.. Here you are not calling next() that's why iteration never moves to the next element and it.hasNext() always returns true..


The next method returns the next object in the collection,and moves you forward to the element you just returned.

hasNext() method returns true if there is an element present after the current element.

so,in this loop,in each iteration you are checking the same object and not moving to the next object.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should move the pointer in the iteration.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic