For this kind of problem, just look at the source code.
@SuppressWarnings({"rawtypes", "unchecked"})
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));
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}
The above is the source code of JDK. The core method is thisshuffle, with some comments removed.
First get the number of elements in the collection. If it is less than 5 or implemented RandomAccess接口,就循环一遍,随机交换集合中两个相邻的元素的位置,RandomAccess is a mark interface. If this interface is implemented, it means that it supports fast random access operations, similar to arrays.
If it is greater than or equal to 5 elements, it is not implemented RandomAccess接口,那么就转为数组,之后也是循环,随机交换集合中两个相邻的元素的位置,最后再将数组放回原来的list.
It is an "approximate" random shuffling of the Collection. The principle is very simple. It is based on a random number generator and randomly interacts with the order of elements of the Collection.
shuffle
搅乱列表顺序,使用Random
生成索引(随机数),将i-1
的元素与随机索引交换。循环collection.size()
times.For this kind of problem, just look at the source code.
The above is the source code of JDK. The core method is this
shuffle
, with some comments removed.First get the number of elements in the collection. If it is less than 5 or implemented
RandomAccess
接口,就循环一遍,随机交换集合中两个相邻的元素的位置,RandomAccess
is a mark interface. If this interface is implemented, it means that it supports fast random access operations, similar to arrays.If it is greater than or equal to 5 elements, it is not implemented
RandomAccess
接口,那么就转为数组,之后也是循环,随机交换集合中两个相邻的元素的位置,最后再将数组放回原来的list
.It is an "approximate" random shuffling of the Collection. The principle is very simple. It is based on a random number generator and randomly interacts with the order of elements of the Collection.