Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16226

Enhanced for loop and iterator in Java

I have a class MyList that implements Iterable interface. And here is a toString() method from one of my classes:

public String toString() {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        // First example using iterator
        for (Iterator<Integer> itr = array[i].iterator(); itr.hasNext();) {
            sb.append(itr.next() + " ");
        }
        // And the same result using enhanced for loop
        for (int val : array[i]) {
            sb.append(val + " ");
        }
    }
    return sb.toString();
}

This loop iterates over the nodes in my list:

for (int val : array[i]) {
    sb.append(val + " ");
}

How does this for loop uses the iterator?

Upvotes: 0

Views: 1770

Answers (3)

Tushar
Tushar

Reputation: 21

When you use an enhanced for loop to iterate over elements in your MyList class, which implements the Iterable interface, Java is actually using the iterator under the hood.

for (int val : array[i]) {
sb.append(val + " ");
}

is syntactic sugar that simplifies iteration. The Java compiler translates this loop into something similar to the following code that explicitly uses an iterator:

for (Iterator<Integer> itr = array[i].iterator(); itr.hasNext();) {
int val = itr.next();
sb.append(val + " ");
}

Upvotes: 1

Naman Gala
Naman Gala

Reputation: 4692

Because your class (MyList) implements Iterable. So internally it will call your iterator() method and then with the use of hasNext() and next() methods of ListIterator it will iterate in for loop.

Refer : Using Enhanced For-Loops with Your Classes

Upvotes: 1

Eran
Eran

Reputation: 393831

The enhanced for loop works for any class that implements Iterable. It internally calls the iterator() method implemented by that class to obtain an Iterator, and uses hasNext() and next() methods of the Iterator to iterate over the elements of the Iterator.

Upvotes: 1

Related Questions