如何在 Java 中打乱一个列表
首先,创建一个整数数组 -
Integer[] strArray = new Integer[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
现在,将其转换为列表 -
List<Integer>list = Arrays.asList(strArray);
使用 Collections 来打乱,如下所示 -
Collections.shuffle(list);
示例
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String args[]) { Integer[] strArray = new Integer[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; List<Integer>list = Arrays.asList(strArray); System.out.println("List = "+list); Collections.shuffle(list); System.out.println("Shuffled List = "+list); } }
输出
List = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Shuffled List = [100, 90, 40, 70, 20, 10, 80, 30, 60, 50]
广告