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

前端 未结 7 896
耶瑟儿~
耶瑟儿~ 2021-01-13 12:32

This is the first time that I\'ve seen this kind of syntax :

// class Node
public class Node { 

...
...

}

public class Otherclass { ... }

Otherclass gra         


        
相关标签:
7条回答
  • 2021-01-13 13:13

    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.

    0 讨论(0)
  • 2021-01-13 13:18

    it is called enhanced for loop, instead of using iterator to iterate over a collection you can simply use this for loop

    using iterators

    Iterator<String> i=a.iterator();
    
    while(i.hasNext())
    {
    String s=i.next();
    }
    

    you can simply use the enhanced for loop.

    for(String s : a)
    {
     .. do something
    }
    

    so it is just a syntactic sugar introduced in Java 5, that do the same functionality of the iterators and it uses the iterator internally. The class should implement the Iterator interface in order to use this for loop

    class Node<T> implements Iterator<String>{
    
    @Override
    public boolean hasNext() {
        // TODO Auto-generated method stub
        return false;
    }
    
    @Override
    public String next() {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public void remove() {
        // TODO Auto-generated method stub
    
    }
    
    
    
    }
    
    0 讨论(0)
  • 2021-01-13 13:26

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

    0 讨论(0)
  • 2021-01-13 13:26

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

    0 讨论(0)
  • 2021-01-13 13:26

    This is one representation of your for loop

    for(int i=0;i<successors.size();i++){
    
            Node myNode = successors.get(i);
        }
    

    This is not a for loop but still you could do this.

    Iterator<Node> itr = successors.iterator();
    
        while(itr.hasNext()){
            Node myNode = itr.next();
            // your logic
        }
    
    0 讨论(0)
  • 2021-01-13 13:30

    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.

    0 讨论(0)
提交回复
热议问题