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?
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.