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 :)

Alan
  • 23
  • 2

4 Answers4

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.

libik
  • 22,239
  • 9
  • 44
  • 87
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]]
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
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));
Holger
  • 285,553
  • 42
  • 434
  • 765
-3
int[][] array = new int[2][3];

The structure is roughly:

[[x, x], [x, x], [x, x]]
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Dame Lyngdoh
  • 312
  • 4
  • 18