Java“for each"循环是如何工作的? [英] How does the Java 'for each' loop work?
问题描述
考虑:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
如果不使用 for each 语法,等效的 for
循环会是什么样子?
What would the equivalent for
loop look like without using the for each syntax?
推荐答案
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
请注意,如果您需要在循环中使用 i.remove();
或以某种方式访问实际迭代器,则不能使用 for ( : )
习惯用法,因为实际的迭代器只是推断出来的.
Note that if you need to use i.remove();
in your loop, or access the actual iterator in some way, you cannot use the for ( : )
idiom, since the actual iterator is merely inferred.
正如丹尼斯·布埃诺 (Denis Bueno) 所指出的,此代码适用于实现 Iterable
接口.
As was noted by Denis Bueno, this code works for any object that implements the Iterable
interface.
此外,如果 for (:)
习惯用法的右侧是 array
而不是 Iterable
对象,则内部code 使用 int 索引计数器并检查 array.length
代替.请参阅 Java 语言规范一>.
Also, if the right-hand side of the for (:)
idiom is an array
rather than an Iterable
object, the internal code uses an int index counter and checks against array.length
instead. See the Java Language Specification.
这篇关于Java“for each"循环是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!