[英]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.