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 myList;// [1,2,3,4]
for (Integer i : myList) {
System.out.println(i.intValue());
}
#output
1,2,3,4
解决方案
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".