public double[] randomSolutions(int[] path) {
double[] doubleSol = new double[vertices];
Random r = new Random();
for (int i = 0; i < doubleSol.length; i++) {
doubleSol[i] = r.nextDouble();
}
return doubleSol;
}
public ArrayList randomDecSol(int[] path) {
ArrayList<double[]> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < 10000; i++) {
list.add(randomSolutions(path));
}
return list;
}
public ArrayList<int[]> doubleToIntArrayList(ArrayList<double[]> list) {
ArrayList<int[]> RandVerArray = new ArrayList<>();
int[] randV = new int[vertices];
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.get(i).length; j++) {
double vertex = ((list.get(i)[j] * 100));
System.out.print(vertex + " ");
randV[j] = (int) Math.round(vertex);
System.out.print(randV[j] + " ");
}
RandVerArray.add(randV);
System.out.print(" \n");
}
return RandVerArray;
}
public void print(ArrayList<int[]> RandVerArray){
for(int[] sol : RandVerArray){
System.out.print(Arrays.toString(sol)+"\n");
}
}
我有这4个函数,第一个函数返回一个充满随机双数的数组,然后我创建了一个ArrayList并运行该函数10000次,并将数组添加到ArrayList中。然后我创建了一个ArrayList,并运行该函数10000次,并将数组添加到ArrayList中。然后我在ArrayList中循环,并将数组中每个索引中的双数乘以100,将数字四舍五入,并将其转换为整数,并重复拥有一个数组列表的过程,但用整数代替。然后我试着打印所有的数字,它只重复打印相同的数字,而这恰好是双数组ArrayList中的最后一个数组。这到底是怎么回事?我想不通。
你实际上是在替换数组中的值。randV
修改代码如下
public ArrayList<int[]> doubleToIntArrayList(ArrayList<double[]> list) {
ArrayList<int[]> RandVerArray = new ArrayList<>();
int[] randV = null;
for (int i = 0; i < list.size(); i++) {
randV = new Integer[vertices];
for (int j = 0; j < list.get(i).length; j++) {
double vertex = ((list.get(i)[j] * 100));
System.out.print(vertex + " ");
randV[j] = (int) Math.round(vertex);
System.out.print(randV[j] + " ");
}
RandVerArray.add(randV);
System.out.print(" \n");
}
return RandVerArray;}