Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java advanced loop : what is (not) evaluated in the loop's header?

Tags:

java

loops

I have the following code:

for (Attribute thisAttribute : factor.getAttributes()) {
// blabla
}

where factor.getAttributes() returns List<Attribute>.

Apparently, there is only one initial call to factor.getAttributes() and then the traversal starts. However, I don't understand why there is only one call. If I were to include a function call in the header of a regular for() loop, I believe it would be evaluated at each iteration. In that respect, how and why is the advanced loop different?

like image 808
James Avatar asked Sep 12 '14 14:09

James


Video Answer


1 Answers

Think of it as getting translated to something like:

{
    Iterator<Attribute> it = factor.getAttributes().iterator();
    while (it.hasNext()) {
        Attribute thisAttribute = it.next();
        // loop body here
    }
}

The compiler knows it gets an Iterable, it can get the Iterator from it once and use it within the loop.

It turns out the Java language specification seems to agree, it says:

The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
    Statement
}
like image 88
Nathan Hughes Avatar answered Oct 09 '22 09:10

Nathan Hughes