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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With