使用Collections API Shuffle
我感到非常沮丧,因为我似乎不知道为什么集合shuffling不能正常工作。
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.
我想说,我试图洗牌 randomizer
数组。
Lets say that I am trying to shuffle the randomizer
array.
int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
由于某种原因,元素保持排序完全相同,无论我是否调用shuffle方法。有任何想法吗?
For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?
Arrays.asList
不能与基元数组一起使用。请改用:
Arrays.asList
cannot be used with arrays of primitives. Use this instead:
Integer[] randomizer = new Integer[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
同样的规则适用于集合框架中的大多数类,因为您不能使用原始类型。
The same rule applies to most classes in the collections framework, in that you can't use primitive types.
原始代码(带有 int []
)编译正常,但没有按预期工作,因为可变参数方法的行为 asList
:它只是一个单元素列表,只有 int
数组
The original code (with int[]
) compiled fine, but did not work as intended, because of the behaviour of the variadic method asList
: it just makes a one-element list, with the int
array as its only member.