import java.util.ArrayList;
2.import java.util.List;
3.import java.util.ListIterator;
4.import java.util.Random;
5.import java.util.RandomAccess;
6.
7.import org.junit.Test;
8./**
9. * Collections随机排序
10. *
11. */
12.public class CollectionsShuffle {
13.
14. private static Random r;
15. private static final int SHUFFLE_THRESHOLD = 5;
16.
17. public static void shuffle(List> list) {
18. if (r == null) {
19. r = new Random();
20. }
21. shuffle(list, r);
22. }
23.
24. public static void shuffle(List> list, Random rnd) {
25. int size = list.size();
26. if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
27. for (int i = size; i > 1; i--)
28. swap(list, i - 1, rnd.nextInt(i));
29. } else {
30. Object arr[] = list.toArray();
31.
32. for (int i = size; i > 1; i--)
33. swap(arr, i - 1, rnd.nextInt(i));
34.
35. ListIterator it = list.listIterator();
36. for (int i = 0; i < arr.length; i++) {
37. it.next();
38. it.set(arr[i]);
39. }
40. }
41. }
42.
43. public static void swap(List> list, int i, int j) {
44. final List l = list;
45. l.set(i, l.set(j, l.get(i)));
46. }
47.
48. private static void swap(Object[] arr, int i, int j) {
49. Object tmp = arr[i];
50. arr[i] = arr[j];
51. arr[j] = tmp;
52. }
53.
54.
55. //初始化List
56. public List initList(){
57. List list = new ArrayList();
58. list.add(1);
59. list.add(2);
60. list.add(3);
61. list.add(4);
62. list.add(5);
63. list.add(6);
64. list.add(7);
65. list.add(8);
66. list.add(9);
67. return list;
68. }
69.
70. //测试Collections随机排序
71. @Test
72. public void testShuffle(){
73. List list = initList();
74. shuffle(list, new Random());
75. for (Integer value : list) {
76. System.out.println(value);
77. }
78. }
79.
80.}