Java 和 C# 中的多维数组
在 C# 中,有两种创建多维数组的方法。
int[,] array1 = new int[32,32];
int[][] array2 = new int[32][];
for(int i=0;i<32;i++) array2[i] = new int[32];
我知道第一个方法在内部创建一个一维数组,第二个方法创建一个数组的数组(访问速度较慢)。
然而在 Java 中,没有 [,] 这样的东西,我看到多维数组是这样声明的:
int[][] array3 = new int[32][32];
由于这种语法在 C# 中是非法的,并且 Java 没有 int[,]
,所以我想知道这是否等同于 array1 ?或者它仍然是数组的数组?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它仍然是一个数组的数组。只是在 C# 中,您必须在循环中创建每个子数组。所以这个 Java:
相当于这个 C#:
(正如 Slaks 所说,锯齿状数组在 .NET 中通常比矩形数组更快。但它们在内存方面效率较低。)
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:
is equivalent to this C#:
(As Slaks says, jagged arrays are generally faster in .NET than rectangular arrays. They're less efficient in terms of memory though.)
你错了;锯齿状(嵌套)数组速度更快。 (CLR 针对它们进行了优化)
Java 不支持真正的多维数组;这是一个锯齿状数组。
Java 语法自动创建所有内部数组;在 C# 中,这需要一个单独的循环。
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.
因为人们关心 .NET 中多维数组与交错数组的性能,所以我实现了一些测试,并对 8k x 8k 元素的结果进行了基准测试:
测试是:
结果:
为了好玩,我也在 WP7 模拟器上运行它们,并得到类似的数字。
测试函数的代码位于此处。
Because people were concerned about the performance of multi-dimension vs staggered arrays in .NET, I implemented a few tests and benchmarked the results on 8k by 8k elements:
The tests were:
And the results:
For fun I ran them on the WP7 emulator as well, and got similar numbers.
Code of the test function is here.
在 Java 中,您正在声明一个数组的数组。
您可以通过以下代码看到这一点:
int[][] arr = new int[3][3];
只是以下代码的简写:In Java you are declaring an array of arrays.
You can see this by the following code:
int[][] arr = new int[3][3];
is just shorthand for:我正在将一些 Java 代码转换为 C# - 这是我如何制作锯齿状数组
I was translating some Java code to C# - here is how I did the Jagged array
它是一个数组的数组,具有与 C# 中相同的性能权衡。
如果您知道数组的数组不会出现锯齿状,那么您可以将其包装在一个类中,以在一维支持数组上获取二维索引。
It is an array of arrays with the same performance tradeoffs as in C#.
If you know that your array of arrays is not going to be jagged, then you can wrap it in a class to get 2-d indexing on a 1-d backing array.