tags:

views:

702

answers:

4

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
+1  A: 

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.

nasufara
yeah but that's really ugly, i'd rather be certain about for-each
Mike
+5  A: 

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>)

rjohnston
+2  A: 

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.

Alex Martelli
+7  A: 

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

http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html

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

http://java.sun.com/javase/6/docs/api/java/util/List.html

hallidave