+ 1

Java iterators

In my below code, how is it displaying all the names? It doesn't look correct to me because my thinking is like this: Iteration 1: it.hasNext() is true So str becomes "one" It goes to "two" Iteration 2: it.hasNext() is true So str becomes "two" It goes to "three" Iteration 3: it.hasNext() is true So str becomes "three" It goes to "four" Iteration 4: it.hasNext() is false so the whole loop ends But this is not what's happening. Plz explain me🥺🥺🥺 https://code.sololearn.com/cUN1R5KtHXkb/?ref=app

26th Aug 2021, 10:58 AM
Rishi
Rishi - avatar
7 Respostas
+ 3
Rishi hasNext is a Boolean method which returns true if next element exist so in your collection next element is "one" so next() method will print it and cursor doesn't move to next line. Again hasNext method will check then returns true if element is exist so next() method will print "two" and so on. Remember next() and nextLine() method are different here we used next() which means current element. Now iteration process is outdated which was used in old java version. In new version we mostly use for each loop or enhanced for loop. for (String s : animals) { } This loop will also do the same thing
26th Aug 2021, 6:34 PM
A͢J
A͢J - avatar
+ 2
I am not sure I understand the question, but remember that the iteration starts from 0 IE: 0 -> one 1-> two 2-> three 3-> four
26th Aug 2021, 11:15 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
hasNext() here does not move cursor public boolean hasNext() { return cursor != size(); } public E next() { E next = get(cursor); cursor++; return next; }
26th Aug 2021, 1:15 PM
zemiak
+ 2
As rightly mentioned by zemiak, the hasNext() method doesn't move the cursor to the next object but the next() method does. So the values returned doesn't depend on the hasNext() but next() instead.
26th Aug 2021, 3:51 PM
Avinesh
Avinesh - avatar
+ 1
Rishi I don't see any issue.
26th Aug 2021, 11:06 AM
A͢J
A͢J - avatar
+ 1
A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ I think you not understand my question. I don't understand how the iteration occurs and what happens with each iteration. See my question description, in my logic, the iteration 3 should be the last iteration and so the last word "four" should not have been printed. Because during the third iteration, the pointer should have moved to fourth word. And so, hasNext(it) should be false(because there is no fifth word). But somehow it is true and the loop executes. I don't understand how that happens In the tutorials it was mentioned that, next() method returns the current element and advances the cursor to next element. Is that correct?
26th Aug 2021, 2:34 PM
Rishi
Rishi - avatar
+ 1
object can use forEach() method if implements iterator in Iterable interface, same with enhanced for()
26th Aug 2021, 7:00 PM
zemiak