The code you show will correctly print all elements of the ArrayList
. The it.next()
call will, at its first call, also the first element. This element is usually denoted with index 0.
Note that you might want to rename arrayOfStrings
as technically it's no array, it's more a List
. A user might due the name think that it is an array.
Documentation
In my opinion you are right that the documentation of the method can be a bit confusing since it is so compact:
Returns the next element in the iteration.
However the description probably needs to be so undetailed since Iterator
is a very frequently used interface, not only for collections. I could imagine a class where the first iteration element should not be the first element of the underlying structure. For example some kind of stream that was already read until a given point. So basically it is up to the implementing class to decide what the first element is. But for collections it will truly be the first element (index 0).
For-each
Also note that the iteration you show is equivalent to how the extended for-loop (for-each) works in Java. So a syntax like
for (Item item : items) {
...
}
will be treated like
Iterator<Item> iter = items.iterator();
while(iter.hasNext()) {
Item item = iter.next();
...
}
In fact this is the reason why you can use everything that implements Iterable
in extended for loops.
Knowing this it would rather be confusing if iter.next()
would skip the first element. I mean by the name for-each is supposed to iterate all elements.
Insights
Let's take a closer look at how the method is implemented. Therefore we will first see what ArrayList#iterator
does. Take a look at its source code:
public Iterator<E> iterator() {
return new Itr();
}
The Itr
class is a private class of ArrayList
(source code). And here is the Itr#next
method:
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
So what it essentially returns is the element at index i
which is where the cursor was at the point of calling the method. It also already advances the cursor by one for the next call of the method.
The cursor however is implicitly initialized with 0
due to:
int cursor; // Default value for int is 0
So the first call of next
will indeed return the element at index 0
which is the first element.