Reputation: 17
I'm just playing around with my code, and was wondering if initializing a multidimensional array with the enhanced for loop is possible.
How do I fix this?
double[][] array2 = new double[2][5];
int b=1;
counter=0;
for(double[] x:array2)
{
for(double a:x)
{
array2[][counter]=b; //<- errors here
counter++;
b+=2;
}
}
//output what it contains
for(double[] x:array2)
{
for(double a:x)
{
System.out.println(a);
}
}
How would you guys do it with 3 dimensions?
double[][][] array3 = new double[4][5][6];
I know I could use Collections for this stuff but I was just trying things out.
Upvotes: 0
Views: 525
Reputation: 298153
Since you need an index to write into an array, you can’t use the enhanced for
loop for updates. However, you are modifying only the innermost arrays in the case of a multi-dimensional array in Java. Therefore you can use the enhanced for
loop for the outer arrays:
double[][] array2 = new double[2][5];
int b=1;
for(double[] x:array2) {
for(int index = 0; index < x.length; index++) {
x[index]=b;
b+=2;
}
}
The same applies to any number of dimensions:
double[][][] array3 = new double[4][5][6];
int b=1;
for(double[][] outer: array3)
for(double[] inner: outer)
for(int index = 0; index < inner.length; index++) {
inner[index]=b;
b+=2;
}
Upvotes: 3
Reputation: 393831
What you are trying to do makes no sense, since you must know the indices of the array in order to assign values to it.
The enhanced for loop hides those indices from you, so you'll have to maintain your own indices, which makes using the enhanced for loop pointless.
Sure, you can do something like this :
int b=1;
int row=0;
for(double[] x:array2)
{
int col=0;
for(double a:x)
{
array2[row][col]=b;
col++;
b+=2;
}
row++;
}
But since you are not using x
and a
, you can just use a regular for loop :
int b=1;
for(int row=0;row<array2.length;row++)
{
for(int col=0;col<array2[row].length;col++)
{
array2[row][col]=b;
b+=2;
}
}
You tell me which version is more readable.
Upvotes: 2