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

25,986

Solution 1

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.

Solution 2

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)

Solution 3

It is the enhanced for statement. See section 14.14.2. The enhanced for statement of the Java Language Specification.

Solution 4

It is called Enhanced for-loop. It basically iterates over a Collection by fetching each element in sequence. So you don't need to access elements on index.

List<Integer> list = new ArrayList<Integer>();

for (int val: list) {
    System.out.println(val);  // Prints each value from list
}

See §14.14.2 - Enhanced for loop section of Java Language Specification.

Solution 5

it means "for each son in successors, where the type of son is Node"

Share:
25,986
JAN
Author by

JAN

The biggest C# and JAVA enthusiastic ever existed.

Updated on March 10, 2021

Comments

  • JAN
    JAN about 3 years

    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

  • Alderath
    Alderath over 11 years
    A for-each loop uses iterators, so it would be more formally correct to say that it can be written as: for (Iterator<Node> it = successors.iterator(); it.hasNext();) { Node son = it.next(); } For the special case of Lists, however, the code example in Anthony's answer is functionally equivalent.
  • Puce
    Puce over 11 years
    But the performance might be a lot worse if you use "get" and the list doesn't support random access.