I'm trying to double the length of a 2D array as I add values to it. I know for a 1D an array the code for this is:
我试着把二维数组的长度增加一倍当我给它添加值的时候。我知道1D和1D数组的代码是:
int oneD[] = new int[10];
//fill array here
oneD = Arrays.copyOf(oneD, 2 * oneD.length);
so if I have a 2D array and only want to double the amount of rows while keeping say 2 columns I figured I would just do this:
如果我有一个二维数组并且只希望使行数加倍同时保持2列我想我应该这样做:
int twoD[][] = new int[10][2];
//fill array here
twoD = Arrays.copyOf(twoD, 2* twoD.length);
This however does not seem to work for the 2D array. How does one go about doubling the length of a 2D array. In this case to make it [20][2] instead.
然而,这似乎不适用于2D数组。如何将二维数组的长度加倍。在本例中,我们将它改为[20][2]。
2 个解决方案
#1
0
In your case something like this would do the job:
在你的情况下,像这样的东西会起作用:
public static <T> T[][] copyOf(T[][] array, int newLength) {
// ensure that newLength >= 0
T[][] copy = new T[newLength][];
for (int i = 0; i < copy.length && i < array.length; i++) {
copy[i] = Arrays.copyOf(array[i], array[i].length);
// this should also work, just not create new array instances:
// copy[i] = array[i];
}
return copy;
}
And you could call this method, just like you called Arrays.copyOf()
你可以调用这个方法,就像你调用array。copyof ()
#2
5
A 2D array in Java is an array of arrays. For doubling it, you'll have to manually iterate over each row in the array and copy all of its columns in turn.
Java中的2D数组是数组的数组。为了使它加倍,您必须手动遍历数组中的每一行,然后依次复制它的所有列。
#1
0
In your case something like this would do the job:
在你的情况下,像这样的东西会起作用:
public static <T> T[][] copyOf(T[][] array, int newLength) {
// ensure that newLength >= 0
T[][] copy = new T[newLength][];
for (int i = 0; i < copy.length && i < array.length; i++) {
copy[i] = Arrays.copyOf(array[i], array[i].length);
// this should also work, just not create new array instances:
// copy[i] = array[i];
}
return copy;
}
And you could call this method, just like you called Arrays.copyOf()
你可以调用这个方法,就像你调用array。copyof ()
#2
5
A 2D array in Java is an array of arrays. For doubling it, you'll have to manually iterate over each row in the array and copy all of its columns in turn.
Java中的2D数组是数组的数组。为了使它加倍,您必须手动遍历数组中的每一行,然后依次复制它的所有列。