1 /*
2 * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 /*
25 * @test
26 * @bug 8294693
27 * @summary Basic test for Collections.shuffle
28 * @key randomness
29 */
30
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.LinkedList;
34 import java.util.List;
35 import java.util.Random;
36 import java.util.function.Consumer;
37 import java.util.random.RandomGenerator;
38
39 public class Shuffle {
40 static final int N = 100;
41
42 public static void main(String[] args) {
43 test(new ArrayList<>());
44 test(new LinkedList<>());
45 }
46
47 static void test(List<Integer> list) {
48 for (int i = 0; i < N; i++) {
49 list.add(i);
50 }
51 Collections.shuffle(list);
52 if (list.size() != N) {
53 throw new RuntimeException(list.getClass() + ": size " + list.size() + " != " + N);
54 }
55 for (int i = 0; i < N; i++) {
56 if (!list.contains(i)) {
57 throw new RuntimeException(list.getClass() + ": does not contain " + i);
58 }
59 }
60 checkRandom(list, l -> Collections.shuffle(l, new Random(1)));
61 RandomGenerator.JumpableGenerator generator = RandomGenerator.JumpableGenerator.of("Xoshiro256PlusPlus");
62 checkRandom(list, l -> Collections.shuffle(l, generator.copy()));
63 }
64
65 private static void checkRandom(List<Integer> list, Consumer<List<?>> randomizer) {
66 list.sort(null);
67 randomizer.accept(list);
68 ArrayList<Integer> copy = new ArrayList<>(list);
69 list.sort(null);
70 if (list.equals(copy)) {
71 // Assume that at least one pair of elements must be reordered during shuffle
72 throw new RuntimeException(list.getClass() + ": list is not shuffled");
73 }
74 randomizer.accept(list);
75 if (!list.equals(copy)) {
76 throw new RuntimeException(list.getClass() + ": " + list + " != " + copy);
77 }
78 }
79 }
--- EOF ---