class="java"> public void test_shuffff() {
List<String> list = Lists.newArrayList( "7451880340:10138652","7451880338:10138652","7451862057:10138652","7451862249:10138652","7451862316:10138652");
Collections.shuffle(list,new Random(10));
System.out.println(list);
}
偶然
发现Collections.shuffle(List,Random)
的时候,多次执行的结果都是一致的,看shuffle的源码里
// Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
怎么也应该是随机的啊!
找寻半天才发现,Random类的说明:
If two instances of {@code Random} are created with the same
* seed, and the same sequence of method calls is made for each, they
* will generate and return identical sequences of numbers
也就是说,如果Random实例的
种子是一样的,那么同样的方法执行结果都是一样的,举例:
public static void main(String[] args) {
Random rd = new Random(10);
System.out.println(rd.nextInt(1));
System.out.println(rd.nextInt(3));
System.out.println(rd.nextInt(4));
System.out.println(rd.nextInt(8));
}
执行多次打印结果都是一致的:
引用0
0
1
3
要注意与不指定种子的Random的区别,默认的Random()是以当前系统时间为种子的,每次执行自然就不一样了