【发布时间】: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