我有m×n矩阵,我需要更改列数(增加或减少)。我有以下代码,但它不起作用。如何增加或减少Java中矩阵的大小?
public class Resize {
public static int [][] A = new int [2][2];
public static int i, j;
public static void main(String[] args) {
A = (int[][])resizeArray(A,4);
for(i = 0 ; i < 2 ; i++){
for(j = 0 ; j < 4 ; j++){
A[i][j] = j+i;
System.out.print(A[i][j]+" ");
}
System.out.println("");
}
}
// resize arr from dimension n = 20 to dimension n = 14 ///////////////
private static Object resizeArray (Object oldArray, int newSize) {
int oldSize = java.lang.reflect.Array.getLength(oldArray);
Class elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(elementType, newSize);
int preserveLength = Math.min(oldSize, newSize);
if (preserveLength > 0)
System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
return newArray;
}
}
“不起作用”不是工作问题描述。除此之外:数组不能调整大小。您只能创建一个全新的阵列并将其分配给现有的阵列,从而有效地丢弃第一个阵列。 – GhostCat