Java为每个循环如何工作? [英] How does the Java 'for each' loop work?
问题描述
考虑:
列表< String> someList = new ArrayList< String>();
//向someList添加monkey,donkey,skeleton key
for(String item:someList){
System.out.println(item);
$ / code>
相当于 c>循环看起来像不使用每个语法的?
for(Iterator< String> i = someList.iterator(); i.hasNext();){
String item = i.next();
System.out.println(item);
$ / code>
请注意,如果您需要使用 i.remove ();
在你的循环中,或以某种方式访问实际的迭代器,你不能使用<:code>只是推断出来的。
正如Denis Bueno指出的,这段代码适用于任何实现 Iterable
界面。
另外,如果(:)成语的右边是
数组<$ code >而不是
Iterable
对象,内部代码使用一个int索引计数器,并相反检查 array.length
。请参阅 Java语言规范。
Consider:
List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
System.out.println(item);
}
What would the equivalent for
loop look like without using the for each syntax?
for (Iterator<String> i = someList.iterator(); i.hasNext();) {
String item = i.next();
System.out.println(item);
}
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.
As was noted by Denis Bueno, this code works for any object that implements the Iterable
interface.
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为每个循环如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!