2014-08-28 36 views
0

我已經編寫了一個函數來插入兩個數組之間的步驟,但是直到插值完成才需要知道所需的步數。在ArrayList中動態生成和存儲基元

這裏是我的功能:

int[][] interpolate(int[] source, int[] goal){ 

    int[] current = new int[source.length]; 
    ArrayList<int[]> steps = new ArrayList<int[]>(); 

    while(/* condition */){ 
     // Change value of current 

     steps.add(current); 
    } 
    int[][] stepsArr = steps.toArray(new int[0][0]); 
    return stepsArr; 
} 

我用一個ArrayList來存儲狀態,因爲我產生他們嘗試過,但摸索出的ArrayList只存儲指針,從而最終ArrayList中包含多個指針到同一個對象(當前的最終值)。

有什麼辦法來動態生成int []實例來存儲在步驟,否則生成一個整數的二維數組?

回答

1

您的問題與您對原始類型的使用無關,但與您對數組的處理無關。通過添加current陣列的副本修復你的代碼,它會正常工作:

steps.add(Arrays.copyOf(current)); 
0

你總是存儲current相同的實例。您可以爲每次迭代創建一個新實例。

int[][] interpolate(int[] source, int[] goal){ 

    int[] current; 
    ArrayList<int[]> steps = new ArrayList<int[]>(); 

    while(/* condition */){ 
     current = new int[source.length]; 
     // Change value of current 

     steps.add(current); 
    } 
    int[][] stepsArr = steps.toArray(new int[0][0]); 
    return stepsArr; 
} 
+0

這打破了代碼:OP迭代地將插值應用於相同的數組。你需要一個前一個數組的副本。 – 2014-08-28 11:02:18