Java 实例 - 集合打乱顺序

Java 教程 · 2019-02-11 16:11:40

以下实例演示了如何使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序:

Main.java 文件

import java.util.*; public class Main { public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) list.add(new Integer(i)); System.out.println("打乱前:"); System.out.println(list); for (int i = 1; i < 6; i++) { System.out.println("" + i + "次打乱:"); Collections.shuffle(list); System.out.println(list); } } }

以上代码运行输出结果为:

打乱前:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第1次打乱:
[2, 0, 5, 1, 4, 9, 7, 6, 3, 8]
第2次打乱:
[2, 6, 4, 8, 5, 7, 9, 1, 0, 3]
第3次打乱:
[6, 5, 1, 0, 3, 7, 2, 4, 9, 8]
第4次打乱:
[1, 3, 8, 4, 7, 2, 0, 6, 5, 9]
第5次打乱:
[3, 0, 7, 9, 5, 8, 4, 2, 1, 6]

点击查看所有 Java 教程 文章: https://www.codercto.com/courses/l/12.html

查看所有标签

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试