2

I recently got into an argument with a friend about the declaration of multidimensional arrays in Java. It would concern the following type of array:

int[][] array = new int[2][3];

So far so good, but one of us sees this array as 2 arrays, each containing 3 elements, and the other see it as 3 arrays, each containing 2 elements. So person A thinks that this is the correct declaration:

int[][] array = new int[][]{{0,1,2},{3,4,5}};

Whereas person B thinks that this is the correct declaration:

int[][] array = new int[][]{{0,1},{2,3},{4,5}};

Who of us is correct? And how could that person prove he's right?

Thanks :)

2

4 Answers 4

2

If you run this code :

    int[][] array = new int[2][3];
    System.out.println(array[0].length);
    System.out.println(array[1].length);

Output is :

3
3

That means, that person A is right.

0

Maybe the following code may shed some light on the way arrays work in Java:

int[][] array=new int[1][3];
int[] sub=array[0];
sub[0]=1; sub[1]=2; sub[2]=42;
System.out.println(Arrays.deepToString(array));
array=new int[2][];
System.out.println(Arrays.deepToString(array));
array[0]=sub; array[1]=sub;
System.out.println(Arrays.deepToString(array));
0

Person A is correct.

This output of this code:

import java.util.Arrays;
public class Test
{
    public static void main(String[] args)
    {
        int[][] array1 = new int[2][3];
        //int[][] array2 = new int[3][2];

        System.out.println(intArray2DToString(array1));
        //System.out.println(intArray2DToString(array2));
    }

    /**
     * Converts a 2D int array to a string
     */
    static String intArray2DToString(int[][] array2D)
    {
        String str = "[";
        for(int[] array : array2D)
        {
            str += Arrays.toString(array);
            str += ", ";
        }
        str += "]";
        str = str.replaceAll(", (?=])", "");
        return str;
    }
}

is:

[[0, 0, 0], [0, 0, 0]]
-3
int[][] array = new int[2][3];

The structure is roughly:

[[x, x], [x, x], [x, x]]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.