Collections.shuffle to accept RandomGenerator

Tagir Valeev amaembo at gmail.com
Tue Sep 27 10:11:35 UTC 2022


Hello!

Currently, Collections.shuffle(List, Random) accepts an outdated
Random class instead of RandomGenerator interface. It looks like,
RandomGenerator would suffice. The code change looks trivial (aside
from documentation and testing), as shuffle() implementation does not
need anything except nextInt:

diff --git a/src/java.base/share/classes/java/util/Collections.java
b/src/java.base/share/classes/java/util/Collections.java
--- a/src/java.base/share/classes/java/util/Collections.java (revision
cab590517bf705418c7376edd5d7066b13b6dde8)
+++ b/src/java.base/share/classes/java/util/Collections.java (date
1664273240190)
@@ -37,6 +37,7 @@
 import java.util.function.IntFunction;
 import java.util.function.Predicate;
 import java.util.function.UnaryOperator;
+import java.util.random.RandomGenerator;
 import java.util.stream.IntStream;
 import java.util.stream.Stream;
 import java.util.stream.StreamSupport;
@@ -454,8 +455,12 @@
      * @throws UnsupportedOperationException if the specified list or its
      *         list-iterator does not support the {@code set} operation.
      */
-    @SuppressWarnings({"rawtypes", "unchecked"})
     public static void shuffle(List<?> list, Random rnd) {
+        shuffle(list, (RandomGenerator) rnd);
+    }
+
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    public static void shuffle(List<?> list, RandomGenerator rnd) {
         int size = list.size();
         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
             for (int i=size; i>1; i--)

What do you think? Should we implement this improvement? I think I can
contribute if there's a general agreement that such an enhancement
would be useful.

With best regards,
Tagir Valeev


More information about the core-libs-dev mailing list