The for/each will always iterate using the natural order for the collection over which it iterates. For an array, as in your example, that would be in index order. For other collection types, a HashMap for example, the natural order may be different (or even unspecified).

For your specific example using an array the answer is yes, predictable order will be observed.

However, in general terms the answer is it depends.

It depends on the Collection type, or more specifically the Iterable type. For example, iterating over an ArrayList will give you a predictable order, but iterating over a HashSet makes no guarantees of order.

Tim Cooke wrote:For your specific example using an array the answer is yes, predictable order will be observed.

However, in general terms the answer is it depends.

It depends on the Collection type, or more specifically the Iterable type. For example, iterating over an ArrayList will give you a predictable order, but iterating over a HashSet makes no guarantees of order.

Wow, never thought it would be the Iterator and not the loop itself.

Campbell Ritchie

Marshal

Posts: 56546

172

posted 1 year ago

3

You can read about the for‑each loop in the Java® Language Specification, though we all know that can be hard to understand.
In the case of arrays the for‑each loop behaves as if it were syntactic sugar forIn the case of Collections the for‑each loop behaves as if it were syntactic sugar forThat assumes the array is T[] and the collection is a Collection<T>.

You cannot iterate a Map but you can get Sets from it which you can iterate, using these three methods: 123.