2017  Kodetalk | Feedback | Privacy Policy | Terms | About

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.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. I want to know what exactly this means.

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


Yes, you can look at the code below

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++) {

The swap method:

private static void swap(Object[] x, int a, int b) {
    Object t = x[a];
    x[a] = x[b];
    x[b] = t;

Answer is