java - 搜索元素并将其添加到数组的 ArrayList
问题描述
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 并将数组的每个索引中的双精度数乘以 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;}
推荐阅读
- javascript - 身份验证后重定向到 Passport.js 中的上一页(不重复)Node.js
- reactjs - 在单个 setState 调用上多次响应状态更新
- pascal - 无法编译 - Turbo Pascal
- mysql - 在 Ubuntu 20.04 上从 MySQL 迁移到 MariaDB
- javascript - d3.js 轴添加刻度值
- git - 写入 node_modules 目录时的管道权限问题
- c++ - 编译错误:Boost.Range / MPL 中没有名为“type”的类型
- java - 构造转换器失败:错误:无法解析 C:
- java - 将类的实例转换为服务(android/Java)时的问题
- ffmpeg - windows上的ffmpeg网络摄像头流到sdl