0

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.

2 Answers 2

3

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;
      }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.