Java 的 foreach 循环是否保留顺序? [英] Does Java's foreach loop preserve order?

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

问题描述

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

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

是否总是首先处理字符串Zoe",然后是Bob"等?没有排序发生?我自己测试过了,没有找到,但我需要保证,但在文档中找不到任何内容.

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.

推荐答案

是的.顺序没有改变.这适用于 Java 集合框架<的所有类型的集合/a> 实现 迭代器接口,即由 for 循环使用.如果要对数组进行排序,可以使用 Arrays.sort(names)

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天全站免登陆