Java advanced loop: what is (un) evaluated in the loop header?

I have the following code:

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

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

Apparently, there is only one initial call to factor.getAttributes() , and then the crawl begins. However, I do not understand why there is only one call. If I included a function call in the header of a regular for() loop, I believe that it will be evaluated at each iteration. In this regard, how and why is there an extended cycle?

+5
source share
1 answer

Think of it as translating into something like:

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

The compiler knows that it gets Iterable, it can get Iterator from it once and use it in a loop.

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

The reinforced for statement is equivalent to the main form expression:

 for (I #i = Expression.iterator(); #i.hasNext(); ) { {VariableModifier} TargetType Identifier = (TargetType) #i.next(); Statement } 
+7
source

Source: https://habr.com/ru/post/1202430/


All Articles