ForEachTraversesRecursiveStructureDRAFT
A for-each loop automatically traverses any given recursive data structure.
For-each loops know how to traverse any recursive data structure
For-each loops only know how to traverse arrays and Iterables
CorrectionHere is what's right.
A for-each loop requires an array or an Iterable
.
Iterable list = //...
for (Object element : list) {
//...
}
While the built-in java.util.LinkedList
class implements Iterable
,
and thus can be traversed directly with a for-each loop,
a recursive data structure that is not a subtype of Iterable
can’t directly be traversed this way.
SymptomsHow do you know your students might have this misconception?
Here, the student believes that the for-each loop will traverse all nodes making up a list:
class Node {
int value;
Node tail;
//...
}
Node head = ...;
for (Node node : head) {
sum += node.value;
}
The following example is similar, but the student believes that the for-each loop will process each value (payload) in the nodes making up a list:
class Node {
int value;
Node tail;
//...
}
Node head = ...;
for (int value : head) {
sum += value;
}