【问题标题】:ArrayStoreException while trying to copy array in java尝试在java中复制数组时出现ArrayStoreException
【发布时间】:2018-02-14 04:52:43
【问题描述】:

我在更改 java 中二维数组的长度时遇到问题。 为二维数组分配空间后,我无法将旧数组的值复制到新数组。但我可以用类似的代码在一维数组上做到这一点。这是工作代码:

public static Object[] changeLength1D(Object [] a, int n, int new_length){

    if(n > new_length){
        throw new IllegalArgumentException("n must be greater or equal to new_length");
    }

    // Allocate space for 1d array
    Object[] new_array = (Object[]) Array.newInstance(a.getClass().getComponentType(), new_length);
    // Efficient array copy from a[0:n-1] to new_array
    System.arraycopy(a, 0, new_array, 0, n);

    return new_array;
}

但同样的逻辑在这里行不通。当我使用 arraycopy 时,java 会抛出这个:

Exception in thread "main" java.lang.ArrayStoreException
at java.base/java.lang.System.arraycopy(Native Method)

这里是二维数组的代码:

public static Object[][] changeLength2D(Object [][] a, int dim1_limit, int dim2_limit,int dim1_newLength, int dim2_newLength){

    if(dim1_limit > dim1_newLength || dim2_limit > dim2_newLength){
        throw new IllegalArgumentException("Limits must be <= new lengths");
    }

    // Allocate space for 2d array
    Object[][] new_array = (Object[][]) Array.newInstance(a.getClass().getComponentType(),
            dim1_newLength,dim2_newLength);


    // Copy by rows
    for(int x = 0; x < dim1_limit; x++){
       System.arraycopy(a[x], 0, new_array[x], 0 ,dim2_limit); // EXCEPTION THROWS RIGHT THIS LINE
    }

    return new_array;
}

【问题讨论】:

  • 实际上我在问这个问题之前就做过,但我已经实施了这个解决方案,这对我的问题不起作用。当我将旧数组的值分配给新数组时,会出现类型问题。

标签: java arrays exception copy


【解决方案1】:

原因

来自Array.newInstance()doc

public static Object newInstance(Class<?> componentType,int... dimensions)
                      throws IllegalArgumentException,
                             NegativeArraySizeException

如果componentType表示一个数组类,则新数组的维数等于dimensions.length和componentType的维数之和

由于您通过以下方式创建二维数组:

Object[][] new_array = (Object[][]) Array.newInstance(a.getClass().getComponentType(),
        dim1_newLength, dim2_newLength);

考虑到a是一个数组,new_array会有三个维度new_array[x]会有两个维度,这会导致ArrayStoreException在运行System.arrayCopy()时因为类型不匹配。

解决方案

使用下面创建新的二维数组并确保a[0][0] 不为空

Object[][] new_array = (Object[][]) Array.newInstance(a[0][0].getClass(),
        dim1_newLength, dim2_newLength);

【讨论】:

  • 非常感谢您的解释和参考链接。
猜你喜欢
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
相关资源
最近更新 更多