Java For-Each循环:排序顺序 [英] Java For-Each Loop : Sort order

查看:394
本文介绍了Java For-Each循环:排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java for-each循环是否保证如果在列表上调用这些元素,它们将按顺序显示?在我的测试中确实如此,但是我似乎找不到任何文档中明确提及的内容

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

推荐答案

是. foreach循环将按iterator()方法提供的顺序遍历列表.请参见关于Iterable接口的文档.

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

如果您查看列表Javadoc 您会看到列表是一个有序集合",并且iterator()方法返回一个按正确顺序"进行迭代的迭代器.

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

这篇关于Java For-Each循环:排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆