Jam*_*ing 4 java collections arraylist
我有一段代码,其想法是它接收一个包含n个数字的数组列表并将其洗牌50次并添加每次将新的shuffle添加到另一个数组列表中.
然而,它似乎要做的就是将其重复一次,将其添加到数组列表中(Like is should),但是对于接下来的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));
}
Run Code Online (Sandbox Code Playgroud)
以下是输出示例:
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]
Run Code Online (Sandbox Code Playgroud)
所以如你所见,它会改变第一个,但不再是.我错过了什么吗?
我错过了什么吗?
是.您错过了在每次迭代中添加相同引用的事实:
for(int j =0; j<50; j++) {
Collections.shuffle(addToFirstChrome);
populationShuffle.add(addToFirstChrome);
}
Run Code Online (Sandbox Code Playgroud)
这实际上与:
for (int j =0; j < 50; j++) {
Collections.shuffle(addToFirstChrome);
}
for (int j = 0; j < 50; j++) {
populationShuffle.add(addToFirstChrome);
}
Run Code Online (Sandbox Code Playgroud)
值addToFirstChrome是只是一个参考.
听起来你想要50个独立的集合,在这种情况下你需要在每次迭代时创建一个新的集合:
for (int j = 0; j < 50; j++) {
List<Integer> copy = new ArrayList<Integer>(addToFirstChrome);
Collections.shuffle(copy);
populationShuffle.add(copy);
}
Run Code Online (Sandbox Code Playgroud)
(请注意,这需要您在可能的情况下更改populationShuffleto List<List<Integer>>或者ArrayList<List<Integer>>- 更喜欢编程到接口的类型.)
| 归档时间: |
|
| 查看次数: |
529 次 |
| 最近记录: |