我以前从未见过这个,你能解释一下这是什么吗??
for(Puzzle p:daughtersList)
.....
.....
Puzzle 是一个类,daughtersList 是一个数组列表
This is the so-called "for each" loop in Java, which has been present since 1.5.
It loops over every element of the Iterable
or array on the right of the colon, with an implicit Iterator
.
It is equivalent to the following code:
for (Iterator<Puzzle> i = daughtersList.iterator(); i.hasNext();) {
Puzzle p = i.next();
// .....
// .....
}
Quoting from Iterable
Javadocs linked above:
Implementing this interface allows an object to be the target of the "foreach" statement.
And lots of things in Java implement Iterable
, including Collection
and Set
, and ArrayList
is a Collection
(and therefore an Iterable
).
这只是编写 for 循环的另一种方法。它被称为“for-each”,因为它遍历列表中的所有项目。例如,每个“拼图”都有一个可通过getName()
方法访问的名称,而您想打印列表中所有拼图的名称。然后你可以这样做:
for(Puzzle p : daugthersList){ // For each Puzzle p, in the list daughtersList
System.out.println(p.getName()); // Print the name of the puzzle
}
它称为 for-each 循环
的右侧:
必须是Iterable
(daughtersList
本质ArrayList
上实现Iterable
了)的实例,此代码才能正常工作
它的一种简短形式
for(Iterator i = daughtersList.iterator(); i.hasNext();) {
Puzzle p = (Puzzle) i.next();
....
}
for(Puzzle p:daughtersList)
是一个foreach
循环。它遍历 daugterlist 的所有元素。在每次迭代中 p 保存当前元素
它是以下类似的替代方案
for(int i = 0; i < daughterList.length(); i++ )
// now use daughetList[i]