Collections

Collections


1. Summary

1. Based on JDK 1.8 2. Reordering elements

in the shuffle() collection



    public static void shuffle(List<?> list) {
        if (r == null) {
            r = new Random();
        }
        shuffle(list, r);
    }
    private static Random r;

    public static void shuffle(List<?> list, Random rnd) {
        int size = list.size();
        // < 5 or an instance of RandomAccess, ArrayList implements the RandomAccess interface
        // as a randomly accessible identifier
        // The instanceof operator is used to indicate at runtime whether an object is an instance of a particular class
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
            for (int i=size; i>1; i--)
                // Swap the element at position i-1 with the element at the random number position
                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]);
            }
        }
    }

    public static void swap(List<?> list, int i, int j) {
	final List l = list;
        // Take the element at position i and place it at position j; similarly
	l.set(i, l.set(j, l.get(i)));
    }



Application: Randomly shuffle the contents of an array

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326703768&siteId=291194637