Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
291 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...