如何随机化ArrayList? [英] How to randomize ArrayList?

查看:131
本文介绍了如何随机化ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个arraylist filelist imgList 与e1.jpg相关的H1.txt。如何根据 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"};


推荐答案

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

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.

这篇关于如何随机化ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆