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?
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.