我有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