Reputation: 107
i have this code, and i would like to know what the ":" mean in the function
Element[][] grid = readFile();
for (Element[] ea : grid) {
for (Element e : ea)
System.out.print(e.getChar());
System.out.println();
Upvotes: 1
Views: 180
Reputation: 1031
This type of loop is called a 'for-each' loop. The colon (:) is read as 'in'. Basically, this type of for loop is used with collections.
It could be read as:-
for each element x in collection Y{
//do something
}
Here, in each iteration, the element x refers to the respective elements in Collection Y. i.e, in first iteration, x will be Y[0], in second iteration, x will be y[1], so on and so forth till the end.
The advantage is that condition checking and all those stuff need not be written explicitly. It is especially useful when iteration elements in a collection sequentially till the end. This makes iterating over collections quite easier. It is easier than making use of iterators.
In your code, each element of the two dimensional array 'ea' is printed, using a nested for-each loop. Outer loop iterates over each row (a single dimensional array), and inner loop iterates over each element in the respective row.
Refer these:-
For-each loop
Related question in stackoverflow
Upvotes: 1
Reputation: 7435
It's simply a divider between the temporary variable and the Iterable
or array.
It's called a foreach
loop, and basically means:
"For each element ae
in Iterable
grid
, do {...}
"
Read more here: The For-Each Loop
Iterable
being an array or a list, for example.
Upvotes: 0
Reputation: 55856
It's a for-each comprehension for Collections and Array. It's same as some languages like Python provide in
functionality. So when you see a :
in a for
loop, read as in
. For more details see this http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
In your case it's like for ea in grid
.
Upvotes: 1
Reputation: 20235
When :
is used in for
, it acts as a for-each loop. Each iteration, the variable after the colon is assigned to the next value in the array.
int[] arr = {1,2,3,4};
for ( arr : num ) {
System.out.print( num + " " );
}
// prints "1 2 3 4 "
Upvotes: 1
Reputation: 882
In terms of a language equivalent, you can think of it as the word "in". You can read it as "for each Element 'e' in 'ea'".
Here's the documentation on that type of loop: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
Upvotes: 4