1. 程式人生 > >JAVA:Collections類的shuffle()方法

JAVA:Collections類的shuffle()方法

JAVA中Collections類的shuffle()方法的作用是將List中的內容隨機打亂順序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

/*
 *Created on 2015年12月23日
 *Copyright 2015 Yong Cai Limited crop. All Rights Reserved
 *
 */

public class CollectionShuffle {

	public static void main(String[] args) {
		List<Integer> li = new ArrayList<Integer>();
		HashSet<Integer> set = new HashSet<Integer>();
		for(int i=0;i < 10;i++){
			li.add(i);
		}
		
		System.out.println(li.toString());
		Random rnd = new Random(2);//給定隨機種子
		for(int j=1;j <= 3;j++){
			Collections.shuffle(li);
			System.out.println(li.toString());
			Collections.shuffle(li, rnd);
			System.out.println("add rnd:"+li.toString());
		}
		
	}

}

輸出結果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[7, 3, 8, 4, 0, 5, 1, 2, 9, 6]
add rnd:[8, 3, 6, 5, 7, 4, 0, 2, 1, 9]
[2, 3, 8, 9, 7, 6, 5, 0, 1, 4]
add rnd:[4, 6, 3, 0, 7, 5, 2, 9, 8, 1]
[9, 2, 8, 7, 0, 5, 3, 6, 1, 4]
add rnd:[2, 0, 6, 7, 8, 3, 5, 4, 1, 9]

shuffle()方法的原始碼如下:
   public static void shuffle(List<?> list) {
        if (r == null) {
            r = new Random();
        }
        shuffle(list, r);
    }
    private static Random r;


    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
            ListIterator it = list.listIterator();
            for (int i=0; i<arr.length; i++) {
                it.next();
                it.set(arr[i]);
            }
        }
    }