How to randomize two ArrayLists in the same fashion?
Solution 1:
Use Collections.shuffle()
twice, with two Random
objects initialized with the same seed:
long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));
Using two Random
objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.
Solution 2:
Wrap them in another class so that you can end up with a single array or List
of those objects.
public class Data {
private String txtFileName;
private String imgFileName;
// Add/generate c'tor, getter/setter, equals, hashCode and other boilerplate.
}
Usage example:
List<Data> list = new ArrayList<Data>();
list.add(new Data("H1.txt", "e1.jpg"));
list.add(new Data("H2.txt", "e2.jpg"));
// ...
Collections.shuffle(list);
Solution 3:
The simplest approach is to encapsulate the two values together into a type which has both the image and the file. Then build an ArrayList
of that and shuffle it.
That improves encapsulation as well, giving you the property that you'll always have the same number of files as images automatically.
An alternative if you really don't like that idea would be to write the shuffle code yourself (there are plenty of examples of a modified Fisher-Yates shuffle in Java, including several on Stack Overflow I suspect) and just operate on both lists at the same time. But I'd strongly recommend going with the "improve encapsulation" approach.
Solution 4:
You could do this with maps:
Map<String, String> fileToImg:
List<String> fileList = new ArrayList(fileToImg.keySet());
Collections.shuffle(fileList);
for(String item: fileList) {
fileToImf.get(item);
}
This will iterate through the images in the random order.
Solution 5:
This can be done using the shuffle method:
private List<Integer> getJumbledList() {
List<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(8);
myArrayList2.add(4);
myArrayList2.add(9);
Collections.shuffle(myArrayList2);
return myArrayList2;