小编典典

如何以相同的方式随机化两个 ArrayList?

all

我有两个相互关联的arraylist filelistimgList例如与“e1.jpg”相关的“H1.txt”。如何imgList根据
的随机化自动随机化列表fileList?就像在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"};

阅读 105

收藏
2022-05-16

共1个答案

小编典典

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

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

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

2022-05-16