Adding multiple “randomly generated” objects to ArrayList results in adding the same object multiple times

问题: I have a class Ttp which has a ArrayList<City>loaded from file. In constructor of Ttp I randomly shuffle a list read from file and assign it to the object. public c...

问题:

I have a class Ttp which has a ArrayList<City>loaded from file. In constructor of Ttp I randomly shuffle a list read from file and assign it to the object.

public class Ttp {
    private ArrayList<City> cities;

    public Ttp() {
        cities = Utils.shuffleArray(Loader.getCities());
    }
}

This way I get 10 objects with nicely shuffled arrays:

public static void main(String args[]) {
    Loader.readFile("easy_0.ttp");
    for(int i=0; i<10; i++){
        System.out.println(new Ttp());
    }
}

But in this scenario, when I try to create ArrayList<Ttp> I get a collection full of the same objects (instances of Ttp with the same arrays of cities)

public static void main(String args[]) {
    Loader.readFile("easy_0.ttp");
    ArrayList<Ttp> arrayList = new ArrayList<>();
    for(int i=0; i<10; i++){
        arrayList.add(new Ttp());
    }
    arrayList.forEach(System.out::println);
}

Shuffle function:

public static <T> ArrayList<T> shuffleArray(ArrayList<T> arrayList) {
    if (arrayList != null && arrayList.size() > 0) {
        int numberOfRolls = Random.getGenerator().nextInt((arrayList.size() - arrayList.size() / 3) + 1) + arrayList.size() / 3;
        int indexA;
        int indexB;
        T objectA;
        for (int i = 0; i < numberOfRolls; i++) {
            indexA = Random.getGenerator().nextInt(arrayList.size());
            indexB = Random.getGenerator().nextInt(arrayList.size());
            objectA = arrayList.get(indexA);
            arrayList.set(indexA, arrayList.get(indexB));
            arrayList.set(indexB, objectA);
        }
    }
    return arrayList;
}

To pick random indexes in shuffle function I am using java.util.Random:

public class Random {
    private static final java.util.Random generator = new java.util.Random();

    public static java.util.Random getGenerator() {
        return generator;
    }
}

回答1:

If Loader.getCities() returns the same list every time that means shuffleArray() is shuffling the same list over and over and every Ttp.cities has a reference to the same unitary list.

The fix is to make a copy somewhere. It could be in getCities(), it could be in shuffleArray(), or it could be in the Ttp constructor:

cities = Utils.shuffleArray(new ArrayList<>(Loader.getCities()));
  • 发表于 2019-03-17 10:22
  • 阅读 ( 212 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除