collections.shuffle(arraylist),此方法可以将arraylist的顺序随机打乱。
打乱原理是,经典的洗牌思想。
洗牌思想是:一副有序的拍,52张。若想打乱这幅牌,可以将第一张牌和后续随机一张牌交换。这样交换52次,此幅牌可以认为是乱序的。
collections.shuffle(arraylist)的源码是:
public static void shuffle(List<?> list) {
Random rnd = r;
if (rnd == null)
r = rnd = new Random(); // harmless race.
shuffle(list, rnd);
}
<pre name="code" class="java">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
// instead of using a raw type here, it's possible to capture
// the wildcard but it will require a call to a supplementary
// private method
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}
private static final int SHUFFLE_THRESHOLD = 5;
该方法的思想是,从最后一张牌开始,每次和他前面随机一张牌交换