This is the first time that I've seen this kind of syntax :
// class Node
public class Node {
...
...
}
public class Otherclass { ... }
Otherclass graph = new Otherclass();
// getSuccessors is a method of Otherclass class
Node currentNode ;
List<Node> successors = graph.getSuccessors(currentNode);
// weird for loop
for (Node son : successors) {
// do something
}
What is that for loop ? some kind of a Matlab syntax ?
Is there any other way to write that for loop ?
Regards
That is a for-each
loop (also called an enhanced-for
.)
for (type var : arr) { //could be used to iterate over array/Collections class
body-of-loop
}
The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each
(Documentation)
It's a for each loop. You could also write it like this:
for(int i = 0; i < successors.size(); i++) {
Node son = successors.get(i);
}
Though the only time I'd personally do that is when the index is needed for doing something other than accessing the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With