Java的foreach循环保持顺序吗? [英] Does Java's foreach loop preserve order?

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

问题描述

Java的foreach循环从第一个对象开始,并以线性方式工作到最后?例如

  String [] names = new String [] {Zoe,Bob,Charlie,Alex }; 
for(String name:names){
// do stuff ...
}

字符串Zoe总是先处理,然后是Bob等?没有排序发生?我已经测试了自己,并没有找到任何,但我需要一个保证,并找不到任何文档。

解决方案

是。订单没有改变。这适用于所有类型的 Java集合框架实现迭代器接口 for循环使用。如果你想排序你的数组,你可以使用 Arrays.sort(names)


Does Java's foreach loop start at the first object and in a linear fashion work it's way to the end? For example

String[] names = new String[] {"Zoe", "Bob", "Charlie", "Alex"};
for(String name : names) {
  //do stuff...
}

Is the string "Zoe" always processed first, followed by "Bob" etc? No sorting happens? I've tested it out myself and haven't found any but I need a guarantee and couldn't find anything in the docs.

解决方案

Yes. The order is not changed. This applies to all types of collections of the Java Collection Framework implementing the iterator interface that is used by the for-loop. If you want to sort your Array, you can use Arrays.sort(names)

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

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