나는 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