2012-10-02 32 views
3

我有一段代碼,它的想法是,它需要一個n數量的數組列表並將其洗牌50次,並且每次添加新的洗牌添加到另一個數組列表。Java collections.Shuffle only shuffling once

然而,它似乎做了一次洗牌,將它添加到數組列表中(像是應該),但接下來的49次,它不洗牌。它只添加相同的一個。 您可以瞭解更多從下面我的代碼:

int chromeSize; 
ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>();  
ArrayList<Integer> addToFirstChrome = new ArrayList<Integer>(); 
ArrayList<ArrayList<Integer>> populationShuffle = new ArrayList<ArrayList<Integer>>(); 

for (int i=0; i<geoPoints.size(); i++) { 
    addToFirstChrome.add(i); 
} 
System.out.println("add To First Chrome " + addToFirstChrome); 

for (int j =0; j<50; j++) { 
    Collections.shuffle(addToFirstChrome); 
    populationShuffle.add(addToFirstChrome); 
} 

for (int p=0;p<populationShuffle.size();p++) { 
    System.out.println("Pop " + p +"=" + populationShuffle.get(p)); 
} 

這裏是輸出的一個示例:

10-02 10:10:26.785: I/System.out(19648): add To First Chrome [0, 1, 2, 3, 4] 
10-02 10:10:26.790: I/System.out(19648): Pop 0=[2, 1, 3, 4, 0] 
10-02 10:10:26.790: I/System.out(19648): Pop 1=[2, 1, 3, 4, 0] 
10-02 10:10:26.790: I/System.out(19648): Pop 2=[2, 1, 3, 4, 0] 
10-02 10:10:26.790: I/System.out(19648): Pop 3=[2, 1, 3, 4, 0] 
10-02 10:10:26.790: I/System.out(19648): Pop 4=[2, 1, 3, 4, 0] 

所以你看,它打亂了第一個,但現在不是了。 我在這裏錯過了什麼嗎?

回答

7

我在這裏錯過了什麼嗎?

是的。你錯過了,你將在每次迭代相同的事實:

for(int j =0; j<50; j++) { 
    Collections.shuffle(addToFirstChrome); 
    populationShuffle.add(addToFirstChrome); 
} 

這是有效一樣:

for (int j =0; j < 50; j++) { 
    Collections.shuffle(addToFirstChrome); 
} 
for (int j = 0; j < 50; j++) { 
    populationShuffle.add(addToFirstChrome); 
} 

addToFirstChrome值是只是參考。

這聽起來像你想50個單獨集合,在這種情況下,你需要創建在每次迭代一個新的集合:

for (int j = 0; j < 50; j++) { 
    List<Integer> copy = new ArrayList<Integer>(addToFirstChrome); 
    Collections.shuffle(copy); 
    populationShuffle.add(copy); 
} 

(請注意,這需要你的populationShuffle的類型更改爲List<List<Integer>>ArrayList<List<Integer>> - 喜歡編程接口儘可能)。

+0

非常感謝你。我可以看到我現在出了什麼地方。 –