简体   繁体   English

如何在Java中复制具有未知列大小的二维数组?

[英]How do I copy a 2d array with an unknown column size in Java?

For school work I need to write a constructor for a class that contains a 2-dimensional array of integers. 对于学校作业,我需要为一个包含二维整数数组的类编写一个构造函数。 The constructor copies a passed in two-dimensional array. 构造函数复制传入的二维数组。 Below is the code I have so far. 下面是我到目前为止的代码。 The current issue I have is how to initialize the array when the "column" size of the passed in array is unknow. 我当前遇到的问题是当传入的数组的“列”大小未知时如何初始化数组。 The issue I think I am having is when creating and initializing the array. 我认为我遇到的问题是在创建和初始化数组时。 The length of the inner and out array is unknown. 内部和外部数组的长度未知。

 public IntMatrix (int[][] array)
    {_matrix = new int [array.length][array.length-1].length];
    for (int i = 0; i < array.length; i++) {
        for(int j=0; j < array[i].length; j++)
        _matrix[i][j]=array[i][j];
    }
}

As I said in a comment, what you have is an array of arrays: 正如我在评论中所说,您拥有的是一个数组数组:

public IntMatrix(int[][] array) {
    matrix = new int[array.length][];
    for (int i = 0; i < array.length; i++) {
        matrix[i] = new int[array[i].length];
        for(int j=0; j < array[i].length; j++) {
            matrix[i][j] = array[i][j];
        }
    }
}

You can always determine the size of an array via myArray.length , so you can allocate for each row/column as you iterate through. 您始终可以通过myArray.length确定数组的大小,因此可以在遍历时为每个行/列进行分配。

A thought, however. 一个想法,但是。 Is it acceptable to simply store the reference to the array that you're passed ? 简单地存储对您传递的数组的引用是否可以接受? Will it change outside your class ? 课外会改变吗? If not, then that might be a simple solution if you don't have to recreate the array internally. 如果没有,那么如果您不必在内部重新创建数组,那么这可能是一个简单的解决方案。

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

相关问题 如何在 Java 中对二维数组进行深拷贝? - How do I do a deep copy of a 2d array in Java? 在Java中,如何获取2D数组的值并将它们存储在具有不同列和行大小的另一个2D数组中? - In Java, how do I take the values of a 2D array and store them in another 2D array with different column and row size? 如何在 Java 中使用循环将二维数组的一行乘以第二个二维数组的列等? - How do I use a loop to multiply a row of a 2D array to the column of a second 2D array, and etc in Java? 如何在Java中的对象内复制2D数组? - How can I copy a 2D Array inside an object in Java? 如何安全地深度复制不规则2D数组线程 - How do I deep copy an irregular 2D array threadsafely 如何从Java中的2D数组中删除特定行和特定列? - How do I remove a specific row and a specific column from a 2D Array in Java? 如何按特定列对java中的int的2D数组进行排序 - how do I sort a 2D array of ints in java by a certain column 如何分别对二维数组的行中的值求和,并分别对列中的值求和? (爪哇) - How do I sum the values in the row of a 2D array separately, and sum the values in the column separately? (Java) 如何检查2D数组列中的字符串? - How do I check strings in a 2D array column? 如何计算参差不齐的二维数组的列长度? - How do I calculate the column length of a ragged 2d array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM