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

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

问题描述

我有两个的ArrayList 文件清单: imgList 这相互关联的,如H1.txt与e1.jpg。如何根据的fileList 的随机自动随机 imgList 的名单?例如,在Excel中,如果我们一定排序列,其它列会自动跟随?

 的String []文件= {H1.txt,H2.txt,H3.txt,M4.txt,M5.txt,M6 。文本};
ArrayList的<串GT;的fileList =新的ArrayList<串GT;(Arrays.asList(文件));串[] IMG = {e1.jpg,e2.jpg,e3.jpg,e4.jpg,e5.jpg,e6.jpg};
ArrayList的<串GT; imgList =新的ArrayList<串GT;(Arrays.asList(IMG));//随机文件
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 };


解决方案

使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List,%20java.util.Random%29\"><$c$c>Collections.shuffle()两次,有两个随机对象使用相同的种子初始化的:

  long种子= System.nanoTime();
Collections.shuffle(的fileList,新的随机(种子));
Collections.shuffle(imgList,新的随机(种子));

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);

output after randomization e.g.:

fileList = {"M4.txt","M6.txt","H3.txt","M5.txt","H2.txt","H1.txt"};

intended output:

 imgList = {"e4.jpg","e6.jpg","e3.jpg","e5.jpg","e2.jpg","e1.jpg"};

解决方案

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));

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

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