Issue
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?
Solution
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.
Answered By - Bill the Lizard
Answer Checked By - Robin (JavaFixing Admin)