C# arrays [,] to Java, concept of specific array

I'm re-writing C# code to Java. I'm facing a type of array not supported by Java. int[,] distance;

So here are my questions, what is this ? [,] Is it the same thing as [ ][ ] ?

I think if I write in java int [ ] [ ] distance; it will work the same way but not sure.

Jon Skeet
people
quotationmark

[,] Is it the same thing as [][] ?

No. I'll use int as the element type to make things simpler. An int[,] is a rectangular array. It's a single object, which is indexed by two dimensions. Each element of the array Note that you can have more dimensions as well, e.g. int[,,] x = new int[10, 20, 30].

There's no concept of accessing "a row" or "a column" of a rectangular array - so

int[,] rectangular = new int[5, 3];
int[] row = rectangular[2]; // Invalid

Compare that with an int[][] - that's an array of arrays, also known as a jagged array. Each element of the array is an int[]... either a null reference, or a reference to an int[] object. Each of the elements may refer to an array of a different length, e.g.

int[][] jagged = new int[][]
{
    new int[0],
    new int[1],
    new int[2]
};

Here, jagged[1][0] is valid, as are jagged[2][1] and jagged[2][2]... but jagged[0][0] would be invalid, as jagged[0] has no elements. And of course you can access individual "rows" in the jagged array:

int[] row = jagged[1];

Note that multiple elements can be the same reference, too. For example:

int[][] jagged = new int[2][];
jagged[0] = new int[1];
jagged[1] = jagged[0];
jagged[0][0] = 10;
System.out.printn(jagged[1][0]); // Also 10! (References to the same array.)

And then of course you mix and match, e.g. int[][,] where each element of the top-level jagged array is a rectangular array. I'd strongly recommend against doing that.

people

See more on this question at Stackoverflow