Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's Collections.shuffle is doing what?

I recently found myself needing to be sure my list wasn't in order. Hibernate was nice enough to return it in perfect order. Silly hibernate, not reading my mind.

I looked at my Java API and it tells me its shuffle method does this:

Randomly permutes the specified list using a default source of randomness.

Being the curious george that I am, I want to know what exactly this means. Is there a math course I can take to learn this? Can I see the code? Java, what are you doing to my ArrayList?!?!?

To be more specific, which math concepts are being used here?

like image 582
Stephano Avatar asked Feb 12 '10 03:02

Stephano


People also ask

What is shuffle in ArrayList?

shuffle() method randomly permutes the list using a default source of randomness. Declaration −The java.util.Collections.shuffle() method is declared as follows − public static void shuffle(List <?> list) Let us see a program to shuffle elements of ArrayList with Java Collections −

Which collection might shuffle the order of inserted elements in Java?

The java. util. Collections class provides shuffle() method which can be used to randomize objects stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order.

Is shuffle available in collections class?

shuffle() Method in Java with Examples. shuffle() method of Collections class as the class name suggests is present in utility package known as java. util that shuffles the elements in the list.


1 Answers

Yes, you can look at the code; it basically does a Fisher-Yates shuffle. Here it is (thanks OpenJDK, and yay for open source :-P):

public static void shuffle(List<?> list, Random rnd) {     int size = list.size();     if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {         for (int i=size; i>1; i--)             swap(list, i-1, rnd.nextInt(i));     } else {         Object arr[] = list.toArray();          // Shuffle array         for (int i=size; i>1; i--)             swap(arr, i-1, rnd.nextInt(i));          // Dump array back into list         ListIterator it = list.listIterator();         for (int i=0; i<arr.length; i++) {             it.next();             it.set(arr[i]);         }     } } 

The swap method:

 private static void swap(Object[] x, int a, int b) {     Object t = x[a];     x[a] = x[b];     x[b] = t; } 
like image 153
Chris Jester-Young Avatar answered Sep 21 '22 11:09

Chris Jester-Young