'For each loop using 2D array
This is the snippet of Java code:
int[][] uu = new int[1][1];
uu[0][0] = 5;
for(int[] u: uu){
System.out.println(u[0]);
}
It prints 5. But why does the declaration part of for loop is declared as int[] u
, but not as int[][] u
?
At the uu you reference 2D array... That is not a homework. I am preparing for Java certification. Cheers
Solution 1:[1]
Since your uu
is an array of array
. So, when you iterate over it, you will first get an array
, and then you can iterate over that array to get individual elements.
So, your outer loop has int[]
as type, and hence that declaration. If you iterate through your u
in one more inner loop, you will get the type int
: -
for (int[] u: uu) {
for (int elem: u) {
// Your individual element
}
}
Solution 2:[2]
It is because uu
is an array of int[]
arrays. So every item in it is int[]
. In a for
loop you declare the type of an item in an array you iterate over.
Solution 3:[3]
The loop is iterating on the elements of uu
, which are objects of type int[]
. (Or in other words - u
is an element in uu
, thus it is an int[]
).
The declaration is always of the type of the objects retrieved by the iteration - in this case - it is int[]
-
Same as iterating over an int[]
is:
for (int x : myArray) { ...}
because each element of x
is of type int
.
Solution 4:[4]
"why does the declaration part of for loop is declared as int[] u, but not as int[][] u?"
The array is two-dimensional, so you are dealing with a double-layered iteration. You have an array "inside" another, in the same principle as List<List<Integer>>
would work.
To iterate through all the elements, you should consider a rows-elements structure. It's necessary that you get each row from the container, and then each element from each row.
for(int[] u: uu)
is simply a for-each iteration rows, with the same principle of for(int row = 0; row < container.length; row++)
, and u
or respectively container[row]
are not elements themselves, but rows (arrays) of elements. Meaning you require a second iteration layer to get the elements:
int[][] container = new int[10][10];
//... - Fill elements.
for(int row = 0; row < container.length; row++){
for(int element = 0; element < container[row].length; element++){
System.out.printf("Row: %d Element: %d Value: %d\n", row, element, container[row][element]);
}
}
Solution 5:[5]
This is an example of finding the sum in 2d array and print it
public class Array2DForEach {
public static void main(String[] args) {
int sum = 0;
int[][] myFirst2DArray = {
{ 3, 5, 1, 9 },
{ 10, 15, 3, 0 },
{ 1, 11, 31, 90 },
{ 2, 51, 1, 9 }
};
for (int[] row:myFirst2DArray) {
for (int columnElement : row) {
sum+=columnElement;
}
}
System.out.println(sum);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | ShyJ |
Solution 3 | amit |
Solution 4 | |
Solution 5 | TarunHacker |