2016-02-27 26 views
0

我有一個算法來計算每個int數組的排列。在這種情況下 - 當我想打印這些排列時 - 一切正常。但是,如果我想將陣列保存到arraylist,它會保存它們的正確數量,但它只保存一個相同的選項。我知道這個問題微不足道,但我解決不了。謝謝你的幫助。int []數組添加到列表的排列

我加入方法printArray,之後它將打印的數組保存到Arraylist。的printArray 輸出是正確的,但printList輸出是這樣的:

1 2 3 4 5 6 

and this input is printed n!, which is correct but its only one permutation

這裏是我的代碼:

公共類置換{

ArrayList<int[]> list; 

public Permute() { 
    list=new ArrayList<>(); 
} 

void printArray(int[] a) { 
    for (int i = 0; i < a.length; i++) { 
     System.out.print(a[i] + " "); 
    } 
    System.out.println(""); 

    list.add(a); 
} 

void printList(){ 
    for(int[] arr:list){ 
     for(int item:arr){ 
      System.out.print(item+" "); 
     } 
     System.out.println(""); 
    } 
} 



void permute(int[] a, int k) { 
    if (k == a.length) 
     printArray(a); 
    else { 
     for (int i = k; i < a.length; i++) { 
      int temp = a[k]; 
      a[k] = a[i]; 
      a[i] = temp; 
      permute(a, k + 1); 
      temp = a[k]; 
      a[k] = a[i]; 
      a[i] = temp; 
     } 
    } 
} 
public static void main(String[] args) { 
    Permute p = new Permute(); 
    int a[] = {1, 2, 3, 4, 5, 6}; 
    p.permute(a, 0); 
    p.printList(); 
} 

}

+1

你總是添加相同的陣列('了')到列表中。稍後對該數組的更改會反映在所有參考中。每次在列表中添加一個'a'的副本:'list.add(Arrays.copyOf(a,a.length))' – schwobaseggl

+0

@schwobaseggl所以當我改變數組a時,它也改變了ArrayList中的數組?我怎樣才能添加副本? – prone666

+0

查看我的更新評論:基本上,您必須爲每個排列(Arrays.copyOf方法所做的)創建一個新數組。一般來說,我會先複製副本,然後進行更改以保持初始數組不受損害。 – schwobaseggl

回答

1

Yo你一次又一次地使用相同的數組。你重新排列它裏面的物品。

打印時很好。但是當你將它保存在一個列表中時,保存的是數組參考,而不是數組內容。

因此,您輸入對同一對象n的引用!次列入清單。在操作結束時,所有這些引用仍然引用相同的對象 - 並且打印列表將一次又一次地打印相同的數組,並使用最近的內容。

如果你想每次保存不同的內容,你需要製作一個複製的數組,並保存該副本。

因此,例如,你可以使用

list.add(Arrays.copyOf(a, a.length)); 
+0

謝謝,我使用a.clone(),它的工作。如此愚蠢的錯誤,哈哈:D – prone666