Reputation: 951
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;
}
}
Upvotes: 2
Views: 289
Reputation: 361710
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()));
Upvotes: 1