This is the first time that I\'ve seen this kind of syntax :
// class Node
public class Node {
...
...
}
public class Otherclass { ... }
Otherclass gra
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.
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
}
}
It is the enhanced for statement. See section 14.14.2. The enhanced for statement of the Java Language Specification.
it means "for each son
in successors
, where the type of son
is Node
"
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
}
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.