How does the Java 'for each' loop work?
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 = someIterable.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.
The construct for each is also valid for arrays. eg
String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };
for (String fruit : fruits) {
// fruit is an element of the `fruits` array.
}
which is essentially equivalent of
for (int i = 0; i < fruits.length; i++) {
String fruit = fruits[i];
// fruit is an element of the `fruits` array.
}
So, overall summary:
[nsayer] The following is the longer form of what is happening:
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.
[Denis Bueno]
It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.
Here is an answer which does not assume knowledge of Java Iterators. It is less precise, but it is useful for education.
While programming we often write code that looks like the following:
char[] grades = ....
for(int i = 0; i < grades.length; i++) { // for i goes from 0 to grades.length
System.out.print(grades[i]); // Print grades[i]
}
The foreach syntax allows this common pattern to be written in a more natural and less syntactically noisy way.
for(char grade : grades) { // foreach grade in grades
System.out.print(grade); // print that grade
}
Additionally this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface.
链接地址: http://www.djcxy.com/p/52984.html上一篇: 传统for循环与Java中的Iterator / foreach的性能
下一篇: 每个'循环'的Java如何工作?