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

This is just an alternative way to write a for-loop. It's called "for-each", because it goes through all the items in your list. An example would be that each "Puzzle" had a name accessible via a getName() method and you wanted to print the names of all the Puzzles in the list. You could then do this:

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

its called for-each loop

The right side of : must be an instance of Iterable (daughtersList is ArrayList which essentially implements Iterable) for this code to work

its a short form of

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