RandomAccess在类Collections的shuffle()方法中的使用:(jdk源码如下)

 1 /**
 2      * Randomly permute the specified list using the specified source of
 3      * randomness.  All permutations occur with equal likelihood
 4      * assuming that the source of randomness is fair.<p>
 5      *
 6      * This implementation traverses the list backwards, from the last element
 7      * up to the second, repeatedly swapping a randomly selected element into
 8      * the "current position".  Elements are randomly selected from the
 9      * portion of the list that runs from the first element to the current
10      * position, inclusive.<p>
11      *
12      * This method runs in linear time.  If the specified list does not
13      * implement the {@link RandomAccess} interface and is large, this
14      * implementation dumps the specified list into an array before shuffling
15      * it, and dumps the shuffled array back into the list.  This avoids the
16      * quadratic behavior that would result from shuffling a "sequential
17      * access" list in place.
18      *
19      * @param  list the list to be shuffled.
20      * @param  rnd the source of randomness to use to shuffle the list.
21      * @throws UnsupportedOperationException if the specified list or its
22      *         list-iterator does not support the <tt>set</tt> operation.
23      */
24     public static void shuffle(List<?> list, Random rnd) {
25         int size = list.size();
26         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
27             for (int i=size; i>1; i--)
28                 swap(list, i-1, rnd.nextInt(i));
29         } else {
30             Object arr[] = list.toArray();
31 
32             // Shuffle array
33             for (int i=size; i>1; i--)
34                 swap(arr, i-1, rnd.nextInt(i));
35 
36             // Dump array back into list
37             ListIterator it = list.listIterator();
38             for (int i=0; i<arr.length; i++) {
39                 it.next();
40                 it.set(arr[i]);
41             }
42         }
43     }
类Collections的shuffle()方法

相关文章: