在Java中,可以使用Collections.shuffle
来随机化或随机化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);
}
}
输出量
[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]
参考文献
翻译自: https://mkyong.com/java/java-how-to-shuffle-an-arraylist/