Collections
一、总结
1.基于 JDK 1.8
二、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(); // < 5 或者是 RandomAccess 的实例,ArrayList 实现 RandomAccess 接口 // 作为可随机访问的标识 // instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例 if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) // 将 i-1 位置的元素与随机数位置的元素调换位置 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]); } } } public static void swap(List<?> list, int i, int j) { final List l = list; // 将i位置的元素取出放在j位置;同理 l.set(i, l.set(j, l.get(i))); }
应用: 随机打乱数组中的内容