Java Collections Shuffle.

时间:2020-02-23 14:37:05  来源:igfitidea点击:

Shuffle方法是默认或者指定的随机性释放传递的列表。

语法

public static void shuffle(List<?> list)
or
public static void shuffle(List<?> list,Random rnd)

示例:让我们在示例的帮助下查看函数。

package org.igi.theitroad;
 
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
 
public class ShuffleMain {
	
	public static void main(String[] args)
	{
		List<String> listOfEmployeeNames = Arrays.asList("John","Martin","Mohan","Mary","Tom");
		
		System.out.println("==========================");
		System.out.println("Before shuffling");
		
		System.out.println(listOfEmployeeNames);
		
		Collections.shuffle(listOfEmployeeNames);
		
		System.out.println("==========================");
		System.out.println("After shuffling");
		
		System.out.println(listOfEmployeeNames);
		
		listOfEmployeeNames = Arrays.asList("John","Martin","Mohan","Mary","Tom");
		Collections.shuffle(listOfEmployeeNames, new Random(3));
		
		System.out.println("==========================");
		System.out.println("After shuffling with randomness of 3");
		
		
		System.out.println(listOfEmployeeNames);
	}
 
}

运行上面的程序时,我们将得到以下输出:

==========================
Before shuffling
[John, Martin, Mohan, Mary, Tom]
==========================
After shuffling
[Mohan, Martin, Mary, Tom, John]
==========================
After shuffling with randomness of 3
[Mary, Martin, John, Mohan, Tom]

Java Collections的内部工作洗牌

Java Collections将Fisher-yates Shuffle中复合时,Shuffle。
它是JDK提供的Shuffle方法的实现。

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]);
        }
    }
}

以下是Swap方法的实现。

private static void swap(Object[] x, int a, int b) {
    Object t = x[a];
    x[a] = x[b];
    x[b] = t;
}