2013-06-24 72 views
2

我想將所有int []數據保存在數組列表中,以便我可以逐步查看每一件事情。只有我的問題是,它覆蓋了我的ArrayList中已有的int []。 我如何填寫我的數組列表而不覆蓋ArrayList中的舊int?數組重寫ArrayList中的數組

ArrayList<int[]> lijstje = new ArrayList<int[]>(); 
    public int[] data = {7,4,8,56,67,85,23,65,23,65,23,22}; 
int stemp; 
int len = 10; 
public void shellSort(){ 
     while (h <= len/3) { 
      h = h * 3 + 1; 
     } 
     while (h > 0) { 

      for (outer = h; outer < len; outer++) { 
       stemp = data[outer]; 
       inner = outer; 

       while (inner > h - 1 && data[inner - h] >= stemp) { 
        data[inner] = data[inner - h]; 
        inner -= h; 
       } 
       data[inner] = stemp; 
       lijstje.add(data); 
      } 
      h = (h - 1)/3; 
     } 
    } 

回答

3

陣列存儲爲引用,所以當您更改數組中的一個地方,其他地方你直接存儲將改變。相反,使用相同的值創建一個全新的數組,並將其存儲。要做到這一點,做array.clone(),這樣對你

ArrayList<int[]> lijstje = new ArrayList<int[]>(); 
public int[] data = {7,4,8,56,67,85,23,65,23,65,23,22}; 
int stemp; 
int len = 10; 
public void shellSort(){ 
    while (h <= len/3) { 
     h = h * 3 + 1; 
    } 
    while (h > 0) { 

     for (outer = h; outer < len; outer++) { 
      stemp = data[outer]; 
      inner = outer; 

      while (inner > h - 1 && data[inner - h] >= stemp) { 
       data[inner] = data[inner - h]; 
       inner -= h; 
      } 
      data[inner] = stemp; 
      lijstje.add(data.clone()); // Notice here how it's data.clone() instead of just data 
     } 
     h = (h - 1)/3; 
    } 
} 

這裏的顯示陣列如何通過引用傳遞了一個例子,這個

int[] original = { 1, 2, 3 }; 
int[] passedByReference = original; 
int[] cloned = original.clone(); 
System.out.println("Before:"); 
System.out.println(Arrays.toString(original)); 
System.out.println(Arrays.toString(passedByReference)); 
System.out.println(Arrays.toString(cloned)); 
original[0]=10; 
System.out.println("After:"); 
System.out.println(Arrays.toString(original)); 
System.out.println(Arrays.toString(passedByReference)); 
System.out.println(Arrays.toString(cloned)); 

會有如下輸出

Before: 
[1, 2, 3] 
[1, 2, 3] 
[1, 2, 3] 
After: 
[10, 2, 3] 
[10, 2, 3] 
[1, 2, 3] 
如你所見,

,克隆的不受影響,而原始的和通過引用的是。在您的代碼中,您不希望對原始文件進行更改以影響您存儲的數組,因此您必須以某種方式克隆它(array.clone()對於2D數組是很好的簡單方法)。

+0

Thx工作完美! :) – Arnout

+0

@亨克燁,樂意幫忙! :) –