Home > Java > javaTutorial > body text

Java example - collection shuffled

黄舟
Release: 2017-01-21 11:05:09
Original
1617 people have browsed it

The following example demonstrates how to use the Collections class Collections.shuffle() method to shuffle the order of collection elements:

/*
 author by w3cschool.cc
 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);
        }
    }}
Copy after login

The output result of the above code is:

打乱前:
[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]
Copy after login


The above is a Java example - a collection of contents in shuffled order. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!