0

i never seen this before can u explain me what is this??

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

Puzzle is a class and daughtersList is an arraylist

  • 2
    That is a [For-Each Loop](http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html). – rid Jun 28 '13 at 18:56
  • [Enhanced For Loop](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2). – Rohit Jain Jun 28 '13 at 18:56
  • It enumerates all Puzzle item in the daughtersList (like foreach in C#) – Dmitry Bychenko Jun 28 '13 at 18:56
  • it helped me to understand this construct by reading it as such: "For each Puzzle p in daughtersList" where p is a temporary variable that each Puzzle will be called as you iterate through all of them – mistahenry Jun 28 '13 at 18:59

4 Answers4

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

rgettman
  • 176,041
  • 30
  • 275
  • 357
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
}
Goatcat
  • 1,133
  • 2
  • 14
  • 31
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();
    ....
}
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

for(Puzzle p:daughtersList) is a foreach loop. It iterate through all the element of daugterlist. in each iteration p holds the current element

it is a similar alternative of the following

for(int i = 0; i < daughterList.length(); i++ )
   // now use daughetList[i]
stinepike
  • 54,068
  • 14
  • 92
  • 112