Java For-Each Loop : Sort order [duplicate]

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".


The foreach loop will use the iterator built into the Collection, so the order you get results in will depend whether or not the Collection maintains some kind of order to the elements.

So, if you're looping over an ArrayList, you'll get items in the order they were inserted (assuming you didn't go on to sort the ArrayList). If you're looping over a HashSet, all bets are off, since HashSets don't maintain any ordering.

If you need to guarantee an order to the elements in the Collection, define a Comparator that establishes that order and use Collections.sort(Collection<T>, Comparator<? super T>).


Yes, the Java language specs ensure that

for (Iterator<Whatever> i = c.iterator(); i.hasNext(); )
    whatEver(i.next());

is equivalent to

for (Whatever x : c)
    whatEver(x);

no "change in ordering" is allowed.


You could use a for loop, a la for (int i = 0; i < myList.length(); i++) if you want to do it in an ordered manner. Though, as far as I know, foreach should do it in order.