如何随机化ArrayList?

问题:

我有两个相互关联的数组列表filelistimgList。 “H1.txt”与“e1.jpg”有关。根据fileList的随机化,如何自动随机化imgList列表?像excel一样,如果我们排序某列,另一列会自动跟随?

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"};

回答:

使用Collections.shuffle()两次,两个Random对象用相同的种子初始化:

long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));

使用具有相同种子的两个Random对象确保两个列表都以完全相同的方式进行混洗。这允许两个单独的集合。

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How to randomize ArrayList?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

5 + 1 =