0

我以前从未见过这个,你能解释一下这是什么吗??

for(Puzzle p:daughtersList)
.....
.....

Puzzle 是一个类,daughtersList 是一个数组列表

4

4 回答 4

1

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).

于 2013-06-28T18:56:11.423 回答
0

这只是编写 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
}
于 2013-06-28T18:56:21.767 回答
0

它称为 for-each 循环

的右侧:必须是IterabledaughtersList本质ArrayList上实现Iterable了)的实例,此代码才能正常工作

它的一种简短形式

for(Iterator i = daughtersList.iterator(); i.hasNext();) {
    Puzzle p = (Puzzle) i.next();
    ....
}
于 2013-06-28T18:56:37.417 回答
0

for(Puzzle p:daughtersList)是一个foreach循环。它遍历 daugterlist 的所有元素。在每次迭代中 p 保存当前元素

它是以下类似的替代方案

for(int i = 0; i < daughterList.length(); i++ )
   // now use daughetList[i]
于 2013-06-28T18:57:36.197 回答