首页  >  文章  >  Java  >  如何在保持顺序一致性的同时随机化多个ArrayList?

如何在保持顺序一致性的同时随机化多个ArrayList?

Barbara Streisand
Barbara Streisand原创
2024-10-27 07:12:02528浏览

How to Randomize Multiple ArrayLists While Maintaining Ordering Consistency?

在随机化期间维持多个 ArrayList 的顺序

随机化单个 ArrayList 是一项简单的任务,但是当多个 ArrayList 相关时,就会出现挑战彼此之间,需要以一致的方式随机化。为了实现这一点,我们可以利用 Collections.shuffle() 和共享随机种子的强大功能。

以下代码片段演示了如何实现所需的结果:

<code class="java">import java.util.ArrayList;
import java.util.Collections;

public class ArrayListRandomization {

    public static void main(String[] args) {
        // Initialize the ArrayLists
        String[] file = {"H1.txt", "H2.txt", "H3.txt", "M4.txt", "M5.txt", "M6.txt"};
        ArrayList<String> fileList = new ArrayList<>(Arrays.asList(file));

        String[] img = {"e1.jpg", "e2.jpg", "e3.jpg", "e4.jpg", "e5.jpg", "e6.jpg"};
        ArrayList<String> imgList = new ArrayList<>(Arrays.asList(img));

        // Generate a shared random seed
        long seed = System.nanoTime();

        // Randomize the file list
        Collections.shuffle(fileList, new Random(seed));

        // Randomize the image list using the same seed
        Collections.shuffle(imgList, new Random(seed));

        // Print the randomized ArrayLists
        System.out.println("Randomized fileList:");
        for (String s : fileList) {
            System.out.println(s);
        }

        System.out.println("Randomized imgList:");
        for (String s : imgList) {
            System.out.println(s);
        }
    }
}</code>

在此代码:

  • 我们使用 System.nanoTime() 获得共享随机种子。
  • 我们使用 Collections.shuffle() 和共享种子来随机化 fileList。
  • 我们使用相同的种子对 imgList 重复随机化过程。

通过使用共享随机种子,两个 ArrayList 以相同的方式随机化,确保维持相应元素之间的关系.

以上是如何在保持顺序一致性的同时随机化多个ArrayList?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn