2017-04-06 71 views
-1

我有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; 
    } 
} 
+1

「不起作用」不是工作問題描述。除此之外:數組不能調整大小。您只能創建一個全新的陣列並將其分配給現有的陣列,從而有效地丟棄第一個陣列。 – GhostCat

回答

1

的問題是,你改變的行數,而不是列在您的resizeArray方法的數量。您可以通過在主要方法的末尾輸出A.length來判斷,它等於二維數組中的行數。行

int oldSize = java.lang.reflect.Array.getLength(oldArray); 

相同設置oldSizeA.length。所以我們都同意oldSize是輸入數組中的行數。然後行

System.arraycopy(oldArray, 0, newArray, 0, preserveLength); 

副本元素oldArray[0]oldArray[1]oldArray[2],... oldArray[preserveLength - 1]newArray[0]newArray[1]newArray[2],... newArray[preserveLength - 1]分別。對於二維數組,您基本上是複製舊數組的行並將其放入新數組中。

一種可能的解決方案可以是通過將元件從舊陣列到新的陣列以使尺寸Math.min(oldArray[0].length, newLength)的通過新陣列的新的數組,然後循環。

private static int[][] resizeArray (int[][] oldArray, int newSize) { 
    int oldSize = oldArray[0].length; //number of columns 
    int preserveLength = Math.min(oldSize, newSize); 
    int[][] newArray = new int[oldArray.length][newSize]; 
    for(int i = 0; i < oldArray.length; i++) { 
     for(int j = 0; j < preserveLength; j++) { 
      newArray[i][j] = oldArray[i][j]; 
     } 
    } 
    return newArray; 
} 
0

您不能將它分配給數組A,因爲它的尺寸已經定義好了。您可以聲明另一個未啓動的數組。

此外我認爲你正在在resizeArray方法太多複雜。除非你想學習反射,否則你可以創建一個新的大小的數組然後複製並返回;