Does Java\'s foreach loop start at the first object and in a linear fashion work it\'s way to the end? For example
String[] names = new String[] {\"Zoe\", \"
Yes. The order is not changed. This applies to all types of collections of the Java Collection Framework implementing the iterator interface that is used by the for-loop. If you want to sort your Array, you can use Arrays.sort(names)
The enhanced for
loop is specified in JLS 14.14.2, where its equivalent code is written.
It can be used to loop over arrays and instances of Iterable
.
For an array, the order of iteration will be always preserved and be consistent between runs. This is because it is equivalent to a simple for
loop with an index going from the beginning of the array to its end.
The enhanced for statement is equivalent to a basic for statement of the form:
T[] #a = Expression; L1: L2: ... Lm: for (int #i = 0; #i < #a.length; #i++) { {VariableModifier} TargetType Identifier = #a[#i]; Statement }
#a
and#i
are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
For an Iterable
, it will follow the order of the corresponding Iterator
(retrieved by calling Iterable.iterator()), that may or may not be consistent between runs.
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 }
#i
is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.
You should refer to the Javadoc of each type to see if an order is consistent or not. For example, it is explicitely specified that for List, the iterator retains the order:
Returns an iterator over the elements in this list in proper sequence.
While it is explicitely specified that for Set, the order is unspecified (unless an extra guarantee is made):
The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).