如何以相同的方式随机化两个ArrayLists? [英] How to randomize two ArrayLists in the same fashion?
问题描述
我有两个相互关联的arraylist filelist
和 imgList
,例如: H1.txt与e1.jpg有关。如何根据 fileList
的随机化自动随机化 imgList
列表?就像在Excel中一样,如果我们对某个列进行排序,另一列会自动跟随吗?
I have two arraylist filelist
and imgList
which related to each other, e.g. "H1.txt" related to "e1.jpg". How to automatically randomized the list of imgList
according to the randomization of fileList
? Like in excel, if we sort certain column, the other column will automatically follow?
String [] file = {"H1.txt","H2.txt","H3.txt","M4.txt","M5.txt","M6.txt"};
ArrayList<String> fileList = new ArrayList<String>(Arrays.asList(file));
String [] img = {"e1.jpg","e2.jpg","e3.jpg","e4.jpg","e5.jpg","e6.jpg"};
ArrayList<String> imgList = new ArrayList<String>(Arrays.asList(img));
//randomized files
Collections.shuffle(fileList);
随机化后输出例如:
fileList = {"M4.txt","M6.txt","H3.txt","M5.txt","H2.txt","H1.txt"};
预期输出:
imgList = {"e4.jpg","e6.jpg","e3.jpg","e5.jpg","e2.jpg","e1.jpg"};
推荐答案
使用 集合.shuffle()
两次,其中两个 Random
对象使用相同的种子初始化:
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));
使用两个带有相同种子的 Random
对象确保两个列表以完全相同的方式进行洗牌。这允许两个单独的集合。
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.
这篇关于如何以相同的方式随机化两个ArrayLists?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!