PM 77-1
PM 77-1

Reputation: 13334

How for-each loop knows where to start?

Iterator is guaranteed to have the following methods:

When for-each loop iterates through iterable class objects, how does it know what object to start with? The above methods provide clear path forward, but what points to the starting element?

For-each guarantees to iterate through all relevant objects. Depending on a class and its next() implementation it could be vitally important where to start (consider forward linked list or any other implementation that has a root element).

How does it work?

If my question does not make sense please explain why.

Upvotes: 2

Views: 1406

Answers (4)

From the spec:

What's officially called the enhanced for statement (for(E e: Iterable<E> iterable)) is translated by the compiler into the equivalent of the following code:

E e;
for(Iterator<E> it = iterable.iterator(); it.hasNext(); ) {
    e = it.next();
    // contents of your for loop
}

The behavior of the loop is exactly as if you'd written it with an explicit Iterator, so the "starting point" of the enhanced for loop is wherever iterable.iterator() would have started anyway.

Upvotes: 2

Marsh
Marsh

Reputation: 8145

This all depends on your collection.

If your collection is a List (ArrayList or LinkedList usually), then the iterator will go in list order according to how they were inserted.

If it is a Map or Set, it is very hard to predict the ordering of its members. If you are using a Map or Set, you should not count on any sort of predictable ordering, in fact, because it doesn't match those collections' purposes. However, LinkedHashMap or LinkedHashSet can be used if you need a specific order but also need the functionality of a Map or Set.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280064

You might want to look at ArrayList's implementation of an Iterator, the Itr inner class.

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @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];
    }
    ...
}

cursor gets initialized to 0 by default. You use cursor to access the elements in the ArrayList object's backing array (it's an inner class, it has access to that field).

Similar logic applies for other implementations of Iterator. It always depends on the underlying data structure. As another example, a Set is not supposed to have an ordering, but it does implement Iterator. A decision has to be made as to where the iterator starts.

Upvotes: 2

Abhijith Nagarajan
Abhijith Nagarajan

Reputation: 4030

foreach is a shorthand for for loop starting from first till last.

Upvotes: 0

Related Questions