Multidimensional arrays in Java and C#

Hannesh picture Hannesh · Mar 15, 2011 · Viewed 7.4k times · Source

In C# there are 2 ways to create mutlidimensional arrays.

int[,] array1 = new int[32,32];

int[][] array2 = new int[32][];
for(int i=0;i<32;i++) array2[i] = new int[32];

I know that the first method creates a 1-dimensional array internally, and that the second method creates an array of arrays (slower access).

However in Java, there is no such thing as [,], and I see multidimensional arrays declared like this:

int[][] array3 = new int[32][32];

Since such syntax is illegal in C#, and Java has no int[,], I'm wondering if this is equivilant to array1? Or is it still an array of arrays?

Answer

Jon Skeet picture Jon Skeet · Mar 15, 2011

It's still an array of arrays. It's just that in C# you'd have to create each subarray in a loop. So this Java:

// Java
int[][] array3 = new int[32][32];

is equivalent to this C#:

// C#
int[][] array3 = new int[32][];
for (int i = 0; i < array3.Length; i++)
{
    array3[i] = new int[32];
}

(As Slaks says, jagged arrays are generally faster in .NET than rectangular arrays. They're less efficient in terms of memory though.)