Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional arrays in Java and C#

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?

like image 449
Hannesh Avatar asked Mar 15 '11 15:03

Hannesh


People also ask

What are multidimensional arrays in C?

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2].... [sizeN];

Does C allow multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

What is multidimensional array in Java?

In Java, a multi-dimensional array is nothing but an array of arrays. 2D array − A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns − Int[][] myArray = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32} }

What are the differences between Java array and C array?

Note that, in Java, arr exists but is null-valued. In C, arr doesn't exist until a complete declaration appears. Array objects in Java must be instantiated with a new operation, and it's there that the array size is specified: int[] arr = new int [10]; int[][] 2Darr = new int[10][20];


1 Answers

You are incorrect; jagged (nested) arrays are faster. (the CLR is optimized for them)

Java does not support true multi-dimensional arrays; that's a jagged array.
The Java syntax automatically creates all of the inner arrays; in C#, that would need a separate loop.

like image 175
SLaks Avatar answered Oct 16 '22 19:10

SLaks