Java – 怎样重新将 ArrayList 重新洗牌(How to shuffle an ArrayList)

来源:互联网 发布:进销存记账软件 编辑:程序博客网 时间:2024/06/10 06:48

在java中,你可以用 Collections.shuffle 取清洗或者重新随机 a ArrayList

TestApp.java
package com.mkyong.utils;import java.util.Arrays;import java.util.Collections;import java.util.List;public class TestApp {    public static void main(String[] args) {        List<String> list = Arrays.asList("A", "B", "C", "D", "1", "2", "3");        //before shuffle        System.out.println(list);        // again, same insert order        System.out.println(list);        // shuffle or randomize        Collections.shuffle(list);        System.out.println(list);        System.out.println(list);        // shuffle again, different result        Collections.shuffle(list);        System.out.println(list);    }}

Output

[A, B, C, D, 1, 2, 3][A, B, C, D, 1, 2, 3][2, B, 3, C, 1, A, D][2, B, 3, C, 1, A, D][C, B, D, 2, 3, A, 1]

References

  1. Collections.shuffle JavaDoc
阅读全文
0 0
原创粉丝点击