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
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
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
).
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
}
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();
....
}
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]