Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does next() method on iterators work?

Tags:

java

iterator

I have a doubt with the next() method on iterators. If I have as a part of my code this lines (with arrayOfStrings size = 4):

Iterator<String> it = arrayOfStrings.iterator(); //arrayOfString is ArrayList<String>

while(it.hasNext()) {
    String e = it.next();
    System.out.println(e);
}

At the very first iteration, the iterator starts pointing to element with index 0? or like the "index -1" ?

I ask because as far as I know the next() method returns the next element in the collection.

So, if at the very first iteration the iterator starts at index 0 when next() is invoked, it returns the element at index 1 and I won´t be able to do nothing with the element at index 0?

like image 792
Angelixus Avatar asked Sep 11 '25 10:09

Angelixus


1 Answers

Think of next as a two-step process. First it gets the next item in the iterator, then it increments the pointer to point to the next item. So, when you create a new iterator, it is initialized to return the first item (index 0) in your list.

like image 165
Bill the Lizard Avatar answered Sep 13 '25 01:09

Bill the Lizard