Java集合。仅洗牌一次
我有一段代码,它的思想是,它接受一个包含n个数字的数组列表,并将其洗牌50次,每次都将新的洗牌添加到另一个数组列表中 然而,它似乎要做的是洗牌一次,将它添加到数组列表中(就像它应该做的那样),但在接下来的49次中,它不会洗牌。它只添加了相同的一个。 您可以从下面的代码中了解更多信息:Java集合。仅洗牌一次,java,collections,arraylist,Java,Collections,Arraylist,我有一段代码,它的思想是,它接受一个包含n个数字的数组列表,并将其洗牌50次,每次都将新的洗牌添加到另一个数组列表中 然而,它似乎要做的是洗牌一次,将它添加到数组列表中(就像它应该做的那样),但在接下来的49次中,它不会洗牌。它只添加了相同的一个。 您可以从下面的代码中了解更多信息: int chromeSize; ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>(); ArrayList<I
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));
}
所以正如你所见,它会洗牌第一个,但不再。
我是不是遗漏了什么
我是不是遗漏了什么
对。您缺少在每次迭代中添加相同引用的事实:
for(int j =0; j<50; j++) {
Collections.shuffle(addToFirstChrome);
populationShuffle.add(addToFirstChrome);
}
for (int j = 0; j < 50; j++) {
List<Integer> copy = new ArrayList<Integer>(addToFirstChrome);
Collections.shuffle(copy);
populationShuffle.add(copy);
}
(请注意,这需要您将
populationShuffle
的类型更改为List
或ArrayList
——如果可能,您更喜欢编程而不是接口。)啊,非常感谢。我知道我现在哪里出错了。
for (int j =0; j < 50; j++) {
Collections.shuffle(addToFirstChrome);
}
for (int j = 0; j < 50; j++) {
populationShuffle.add(addToFirstChrome);
}
for (int j = 0; j < 50; j++) {
List<Integer> copy = new ArrayList<Integer>(addToFirstChrome);
Collections.shuffle(copy);
populationShuffle.add(copy);
}