Home  >  Q&A  >  body text

java - Collections.shuffle

ringa_leeringa_lee2728 days ago606

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:09:02

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

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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:09:02

    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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:09:02

    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.

    reply
    0
  • Cancelreply