Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in the form of : "for (A b : c)" in Java

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

like image 987
JAN Avatar asked Nov 28 '22 21:11

JAN


2 Answers

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)

like image 55
Anirudh Ramanathan Avatar answered Dec 15 '22 03:12

Anirudh Ramanathan


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.

like image 33
Anthony Grist Avatar answered Dec 15 '22 03:12

Anthony Grist