Java For-Each Loop : Sort order

java, loops, syntax

Solution

Yes. The foreach loop will iterate through the list in the order provided by the `iterator()` method. See the documentation for the Iterable interface.

If you look at the Javadoc for List you can see that a list is an "ordered collection" and that the `iterator()` method returns an iterator that iterates "in proper sequence".

Problem

Does a java for-each loop guarantee that the elements will be presented in order if invoked on a list? In my tests it does seem to, but I can't seem to find this explicitly mentioned in any documentation ``` List<Integer> myList;// [1,2,3,4] for (Integer i : myList) { System.out.println(i.intValue()); } #output 1,2,3,4 ```

Original source

Related problems