简体   繁体   English

如何在 Java 中创建一个锯齿状的二维数组?

[英]How do I create a jagged 2d array in Java?

Our homework assignment asks us to use a jagged array to store the values of a two dimensional boolean matrix.我们的家庭作业要求我们使用锯齿状数组来存储二维布尔矩阵的值。 Is there a built in java class for the jagged array or am I going to have to manually create it with an Array of ArrayLists ?是否有用于锯齿状数组的内置 java 类,还是我必须使用ArrayLists Array手动创建它?

In Java, a 2D array is an array of 1D array objects.在 Java 中,二维数组是一维数组对象的数组。 Each 1D array can have different length, which means that you get jagged arrays out of the box.每个一维数组可以有不同的长度,这意味着您可以立即使用锯齿状数组。

For example, the following is perfectly valid Java, and prints out 3 5 3 4 :例如,以下是完全有效的 Java,并打印出3 5 3 4

    int x[][] = {{0,1,2,3,4},{0,1,2},{0,1,2,3}};
    System.out.println(x.length);
    System.out.println(x[0].length);
    System.out.println(x[1].length);
    System.out.println(x[2].length);

It actually sounds like you might want a sparse matrix implementation.实际上听起来您可能想要一个稀疏矩阵实现。 You can get much better performance out of it if you are having to modify the matrix.如果您必须修改矩阵,您可以获得更好的性能。 Array copy operations are pretty expensive.数组复制操作非常昂贵。 Sparse matrices / arrays in Java Java 中的稀疏矩阵/数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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