0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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 + " ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.