-1

Using Java's enhanced for loop, I have for quite some time avoided using the structure if I needed the processing to be in any particular order (for example: printing out the values in a table in the same order as the collection). It seems obvious that that should be the case, but on the other hand, the syntax of the structure seems to imply that I should not rely or know about that.

Perhaps embarrassingly, I have not been able to track down any documentation that explicitly says enhanced for loops are processed in first-to-last order. Does such documentation exist, and if so, where can I find it?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Daniel R. Collins
  • 893
  • 1
  • 8
  • 22
  • I don't know where to find the documentation, but I strongly believe that enhanced for loops are always processed in first to last order – ControlAltDel Jun 27 '17 at 14:12

2 Answers2

1

Perhaps embarrassingly, I have not been able to track down any documentation that explicitly says enhanced for loops are processed in first-to-last order. Does such documentation exist, and if so, where can I find it?

The authoritative reference for Java language syntax and semantics is the Java Language Specification. If your search for docs did not take you there then perhaps a bit of embarrassment is indeed in order. Section 14.14.2 of JLS 8 covers the semantics of the enhanced for loop. I do not quote it here, but it covers two cases:

  • When the for loop's iteration is over an Iterable, it obtains that object's iterator and processes elements in the order that they are returned by the iterator's next() method.

  • When the for loop's iteration is over an array, it processes elements in order by index, starting at 0.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

The order of the enhanced for loop depends on the Iterator of the Collection to loop through. so as long as this returns the objects in the correct order, the for loop will work as expected: https://blogs.oracle.com/corejavatechtips/using-enhanced-for-loops-with-your-classes

Florian S.
  • 386
  • 1
  • 12