详细来说,Java 中的“foreach”循环是如何工作的?

2023-12-09

考虑:

List<String> someList = new ArrayList<>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
    System.out.println(item);
}

相当于什么for循环看起来像不使用for each syntax?


People new to Java commonly encounter issues when trying to modify the original data using the new style foreach loop. Use Why doesn't assigning to the iteration variable in a foreach loop change the underlying data? to close duplicates about that common problem. Note that other languages with analogous constructs generally have the same issue; for example, see Why doesn't modifying the iteration variable affect subsequent iterations? for the same issue in Python.


for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}

请注意,如果您需要使用i.remove();在你的循环中,或者以某种方式访问​​实际的迭代器,你不能使用for ( : )习语,因为实际的迭代器只是推断出来的。

正如 Denis Bueno 所指出的,此代码适用于任何实现Iterable界面.

另外,如果右侧for (:)成语是一个array而不是一个Iterable对象,内部代码使用 int 索引计数器并检查array.length反而。请参阅Java语言规范.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

详细来说,Java 中的“foreach”循环是如何工作的? 的相关文章

随机推荐