Java For-Each 循环:排序顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1376934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java For-Each Loop : Sort order
提问by Mike
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
java for-each 循环是否保证如果在列表上调用元素将按顺序显示?在我的测试中似乎确实如此,但我似乎无法在任何文档中明确提到这一点
List<Integer> myList;// [1,2,3,4]
for (Integer i : myList) {
System.out.println(i.intValue());
}
#output
1,2,3,4
采纳答案by hallidave
Yes. The foreach loop will iterate through the list in the order provided by the iterator()
method. See the documentation for the Iterable interface.
是的。foreach 循环将按照iterator()
方法提供的顺序遍历列表。请参阅Iterable 接口的文档。
If you look at the Javadoc for Listyou can see that a list is an "ordered collection" and that the iterator()
method returns an iterator that iterates "in proper sequence".
如果您查看List的Javadoc,您会发现列表是一个“有序集合”,并且该iterator()
方法返回一个“按正确顺序”迭代的迭代器。
回答by Mike
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.
您可以使用 for 循环,for (int i = 0; i < myList.length(); i++)
如果您想以有序的方式进行,则可以使用 la 。不过,据我所知,foreach 应该按顺序执行。
回答by rjohnston
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.
该foreach
循环将使用内置的迭代器Collection
,所以为了你得到的结果将取决于是否Collection
保持某种的元素顺序。
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.
因此,如果您循环遍历ArrayList
,您将按照插入的顺序获取项目(假设您没有继续对 ArrayList 进行排序)。如果您在 a 上循环HashSet
,则所有赌注都将关闭,因为 HashSets 不保持任何顺序。
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>)
.
如果您需要保证 Collection 中元素的顺序,请定义Comparator
建立该顺序并使用Collections.sort(Collection<T>, Comparator<? super T>)
.
回答by Alex Martelli
Yes, the Java language specs ensure that
是的,Java 语言规范确保
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.
不允许“更改顺序”。