java - Collections.shuffle
ringa_lee
ringa_lee 2017-04-18 10:07:02
0
3
599
ringa_lee
ringa_lee

ringa_lee

reply all(3)
大家讲道理

    for (int i=size; i>1; i--)
        swap(list, i-1, rnd.nextInt(i));

shuffle搅乱列表顺序,使用Random生成索引(随机数),将i-1的元素与随机索引交换。循环collection.size() times.

洪涛

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!