[ACCEPTED]-Java For-Each Loop : Sort order-loops

Accepted answer
Score: 48

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

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

Score: 15

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

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

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

Score: 10

Yes, the Java language specs ensure that

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

is 2 equivalent to

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

no "change in ordering" is 1 allowed.

Score: 3

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

More Related questions