1. 自己实现
从最高位起,最高位与后面的随机一位进行交换,交换后最高位就是随机后的,固定再不动,逐次for循环
int length = arr.length;
for ( int i = length; i > 0; i-- ){
int randInd = rand.nextInt(i);
swap(arr, randInd, i - 1);
}
2. jdk(Collections.shuffle)
public static void shuffle(List<?> list) {
Random rnd = r;
if (rnd == null)
r = rnd = new Random(); // harmless race.
shuffle(list, rnd);
}
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]);
}
}
}