简体   繁体   English

Java - 创建与另一个2D阵列大小相同的2D阵列

[英]Java - Creating 2D Array with same size as another 2D Array

I have the following 2D Array: 我有以下2D数组:

     int[][] matrixA = { {1, 2 ,3}, {4, 5, 6} };

And I want to create another 2D Array with the same size of matrixA , my question is how do I do it with, the same way of an ordinary array, ie, int[] arrayA = {10, 12, 33, 23}, int[] arrayB = new int[arrayA.length] 我想创建另一个具有相同大小的matrixA 2D数组,我的问题是如何使用,与普通数组相同,即int[] arrayA = {10, 12, 33, 23}, int[] arrayB = new int[arrayA.length]

    int[][] matrixB = new int[matrixA.length][]

Can I do it like this, only alocating one array with two positions and and leaving the rest to be filled with a for loop? 我可以这样做,只将一个阵列分配到两个位置,并让其余阵列填充for循环吗? Or there's a more correct and flexible way to do this? 或者有更正确和灵活的方法来做到这一点?

Why not just use the ordinary multidimensional array initialization syntax? 为什么不直接使用普通的多维数组初始化语法?

    int[][] a = {{1,2,3}, {4,5,6}};
    int[][] b = new int[a.length][a[0].length];

This seems to work perfectly well. 这看起来效果很好。 Here is a little loop that tests that all entries are indeed present, and that we don't get any AIOOBEs: 这是一个小循环,测试所有条目确实存在,并且我们没有获得任何AIOOBE:

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[0].length; j++) {
          b[i][j] = a[i][j];
        }
    }

This, obviously assumes that you are dealing with rectangular matrices, that is, all rows must have the same dimensions. 这显然假设您正在处理矩形矩阵,即所有行必须具有相同的尺寸。 If you have some weird jagged arrays, you must use a loop to initialize each row separately. 如果你有一些奇怪的锯齿状数组,你必须使用一个循环来分别初始化每一行。

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

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