简体   繁体   中英

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.

[,] 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, eg 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, eg

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, eg int[][,] where each element of the top-level jagged array is a rectangular array. I'd strongly recommend against doing that.

It's not exactly the same, but it's the mapping that exists. It will work the same way for your application.

The key difference is that the C# [,] syntax guarantees a rectangular array, and the C# and Java [][] syntax allows jagged arrays unless you guarantee each inner array is the same length.

If you are using slicing of the multi-dimension array in C#, you'll need to create or use helper functions to get that same functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM