Collections.shuffle函数的实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013278314/article/details/84170547

shuffle是用来随机打乱元素位置的

下面是使用示例:

public class ShuffleTest {  
    public static void main(String[] args) {  
        List<Integer> list = new ArrayList<Integer>();  
        for (int i = 0; i < 10; i++)  
            list.add(new Integer(i));  
        System.out.println("打乱前:");  
        System.out.println(list);  
  
        for (int i = 0; i < 5; i++) {  
            System.out.println("第" + i + "次打乱:");  
            Collections.shuffle(list);  
            System.out.println(list);  
        }  
    }  
}  

输出结果:

打乱前:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
第0次打乱:
[6, 3, 2, 0, 8, 1, 7, 5, 4, 9]
第1次打乱:
[6, 2, 3, 0, 8, 5, 7, 4, 9, 1]
第2次打乱:
[1, 7, 9, 4, 6, 0, 2, 5, 3, 8]
第3次打乱:
[0, 4, 2, 8, 9, 1, 3, 7, 5, 6]
第4次打乱:
[8, 1, 3, 0, 7, 9, 4, 2, 5, 6]
 

进一笔分析源码看看是怎么实现的:

public static void shuffle(List<?> list, Random rnd) {
        // 集合大小
        int size = list.size();
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { // 小于shuffle阈值(SHUFFLE_THRESHOLD 等于5)或者可以随机访问(如ArrayList,访问效率很高)
            // 从后往前遍历
            for (int i=size; i>1; i--)
                // 交换指定位置的两个元素
                swap(list, i-1, rnd.nextInt(i));
        } else { // 如果大于阈值并且不支持随机访问,那么需要先转化为数组,再进行处理
            Object arr[] = list.toArray(); // 该数组只是中间存储过程
            // 从后往前遍历
            for (int i=size; i>1; i--)
                // 交换指定位置的两个元素
                swap(arr, i-1, rnd.nextInt(i));
            // 重新设置list的值
            ListIterator it = list.listIterator();
            // 遍历List
            for (int i=0; i<arr.length; i++) {
                it.next();
                it.set(arr[i]);
            }
        }
    }

说明:从源码可知,进行shuffle时候,是分成两种情况。

  1. 若集合元素个数小于shuffle阈值或者集合支持随机访问,那么从后往前遍历集合,交换元素。

  2. 否则,先将集合转化为数组(提高访问效率),再进行遍历,交换元素(在数组中进行),最后设置集合元素。

  其中涉及的swap函数如下,两个重载函数

public static void swap(List<?> list, int i, int j) {
        // 交换指定位置的两个元素
        final List l = list;
        l.set(i, l.set(j, l.get(i)));
    }

    private static void swap(Object[] arr, int i, int j) {
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

猜你喜欢

转载自blog.csdn.net/u013278314/article/details/84170547
今日推荐