Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二维数组的双行长度_Java_Arrays - Fatal编程技术网

Java 二维数组的双行长度

Java 二维数组的双行长度,java,arrays,Java,Arrays,我试图在向2D数组添加值时将其长度加倍。我知道对于一维数组,其代码是: int oneD[] = new int[10]; //fill array here oneD = Arrays.copyOf(oneD, 2 * oneD.length); 因此,如果我有一个2D数组,只想将行数增加一倍,同时保留2列,我想我会这样做: int twoD[][] = new int[10][2]; //fill array here twoD = Arrays.copyOf(twoD, 2* two

我试图在向2D数组添加值时将其长度加倍。我知道对于一维数组,其代码是:

int oneD[] = new int[10];
//fill array here

oneD = Arrays.copyOf(oneD, 2 * oneD.length);
因此,如果我有一个2D数组,只想将行数增加一倍,同时保留2列,我想我会这样做:

int twoD[][] = new int[10][2];
//fill array here

twoD = Arrays.copyOf(twoD, 2* twoD.length);

但是,这似乎不适用于二维阵列。如何将二维阵列的长度加倍。在本例中,将其改为[20][2]。Java中的2D数组是数组的数组。要将其加倍,您必须手动迭代数组中的每一行,并依次复制其所有列。

在您的情况下,类似这样的操作可以完成以下任务:

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;
}
public static T[][]copyOf(T[][]数组,int newLength){
//确保newLength>=0
T[][]复制=新T[newLength][];
对于(int i=0;i

你可以调用这个方法,就像你调用的
Arrays.copyOf()

看起来应该可以,但我一直在Arrays.copyOf部分获取ArrayIndexOutofBounds异常抱歉,没有引起足够的注意。我更新了for循环条件以修复(明显的)错误。。。