Java设计二维数组

发布于 2024-09-27 23:37:26 字数 206 浏览 0 评论 0原文

我有一个二维数组。是否有必要固定大小以使每行具有相同的列数?

data = {{ 2, 6, 3, 3, 1 }, 
        { 4, 6, 3, 7, 5 }, 
        { 8, 3, 0, 0, 0}, 
        { 13, 12, 0, 0, 0 }, 
        { 5, 1, 3, 9, 5, 0}} 

I have a 2 dimensional array. Is it necessary to fix the size so that every row has the same number of columns?

data = {{ 2, 6, 3, 3, 1 }, 
        { 4, 6, 3, 7, 5 }, 
        { 8, 3, 0, 0, 0}, 
        { 13, 12, 0, 0, 0 }, 
        { 5, 1, 3, 9, 5, 0}} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遗失的美好 2024-10-04 23:37:26
{{ 0, 2, 6, 3, 3, 1 },
 { 1, 4, 6, 3, 7, 5 },
 { 0, 8, 3 },
 { 1, 13, 12 },
 { 0, 5, 1, 3, 9, 5 }}

Java 中的数组数组不一定是“矩形”。只需去掉哨兵 (-1) 和它们后面的“空”数据,并使用子数组的 .length 即可。

{{ 0, 2, 6, 3, 3, 1 },
 { 1, 4, 6, 3, 7, 5 },
 { 0, 8, 3 },
 { 1, 13, 12 },
 { 0, 5, 1, 3, 9, 5 }}

Arrays of arrays in Java do not have to be "rectangular". Just get rid of the sentinel (-1) and the "empty" data after them and use the .length of the sub-array.

场罚期间 2024-10-04 23:37:26

您可以忽略所有被忽略的值; java 2d 数组只是数组的数组。没有理由要求它们都具有相同的长度。

You can just omit all the ignored values; a java 2d array is just an array of arrays. There's no reason why they have to all be the same length.

溺ぐ爱和你が 2024-10-04 23:37:26

不,没有必要固定 java 二维数组中每行的列大小。

作为“TofuBeer”答案的扩展,您可以动态分配二维数组,如下所示。下面的示例显示了三角矩阵:

int[][] array2D;

//Allocate each part of the two-dimensional array individually.
array2D = new int[10][];        // Allocate array of rows
for (int r=0; r < array2D.length; r++) {
    array2D[r] = new int[r+1];  // Allocate a row
}

//Print the triangular array (same as above really)
for (int r=0; r<array2D.length; r++) {
    for (int c=0; c<tarray2D[r].length; c++) {
        System.out.print(" " + array2D[r][c]);
    }
    System.out.println("");
}

No, it is not necessary to fix the size for the columns for each row in java's 2D array.

In extension to the answer of "TofuBeer" you can allocate the 2D array dynamically as below. the below sample shows the trangular matrix:

int[][] array2D;

//Allocate each part of the two-dimensional array individually.
array2D = new int[10][];        // Allocate array of rows
for (int r=0; r < array2D.length; r++) {
    array2D[r] = new int[r+1];  // Allocate a row
}

//Print the triangular array (same as above really)
for (int r=0; r<array2D.length; r++) {
    for (int c=0; c<tarray2D[r].length; c++) {
        System.out.print(" " + array2D[r][c]);
    }
    System.out.println("");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文