首页 > 解决方案 > 搜索元素并将其添加到数组的 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 中的最后一个数组。这里发生了什么?我想不通。

标签: javaarraylist

解决方案


您实际上是在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;}

推荐阅读