# Collections 随机排序方法Shuffle源码说明

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.RandomAccess;

import org.junit.Test;
/**
* Collections随机排序
*
*/
public class CollectionsShuffle {

private static Random r;
private static final int SHUFFLE_THRESHOLD = 5;

public static void shuffle(List<?> list) {
if (r == null) {
r = new Random();
}
shuffle(list, 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();

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

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

//初始化List
public List<Integer> initList(){
List<Integer> list = new ArrayList<Integer>();
return list;
}

//测试Collections随机排序
@Test
public void testShuffle(){
List<Integer> list = initList();
shuffle(list, new Random());
for (Integer value : list) {
System.out.println(value);
}
}

}


#### 使用Collections类中shuffle随机打乱List内部元素顺序

2013-12-19 14:12:16

#### java实现数组随机重新排列

2017-06-01 13:24:41

#### Java随机不重复排序算法

2011-04-01 14:53:00

#### Java中对List集合内的元素进行顺序、倒序、随机排序的示例代码

2017-05-09 10:49:11

#### java随机排列数组

2009-12-04 16:43:00

#### Java 集合深入理解（4）：List<E> 接口

2016-10-13 01:34:49

#### 关于Collections.shuffle()方法的学习

2016-04-22 12:28:25

#### JAVA：Collections类的shuffle()方法

2015-12-23 21:09:21

#### JAVA的Collections类中shuffle的用法

2011-03-27 20:26:00

#### Collections shuffle 随机排序

2016-06-15 10:42:17