使用 Collections API 进行随机播放
我感到非常沮丧,因为我似乎无法弄清楚为什么集合洗牌无法正常工作。
假设我正在尝试对随机化器数组进行洗牌。
int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
由于某种原因,无论我是否调用 shuffle 方法,元素的排序都完全相同。 有任何想法吗?
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.
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));
For some reason the elements stay sorted exactly the same whether or not I call the shuffle method. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
克里斯的回答是正确的。
正如我在对 Chris 的回答的评论中所说,除非 arraylist 需要增长,否则您的底层数组将适当更改,并且列表会创建一个新数组并将项目复制到其中。
您可能希望保留对列表的引用,并在 Arrays.asList 调用之后迭代该列表,然后不再迭代数组,而是迭代 List。
Chris' answer is correct.
As i said in a comment on Chris' answer, your underlying array will change appropriately unless the arraylist needs to grow, and the list creates a new one and copies items into it.
You may want to keep a reference to the list and iterate over that after the Arrays.asList call, and not iterate over the array after that, iterate over the List instead.
Arrays.asList
不能与基元数组一起使用。 请使用此替代:相同的规则适用于集合框架中的大多数类,因为您不能使用原始类型。
原始代码(使用
int[]
)编译得很好,但由于可变参数方法asList
的行为而没有按预期工作:它只生成一个元素列表,int
数组作为其唯一成员。Arrays.asList
cannot be used with arrays of primitives. Use this instead:The same rule applies to most classes in the collections framework, in that you can't use primitive types.
The original code (with
int[]
) compiled fine, but did not work as intended, because of the behaviour of the variadic methodasList
: it just makes a one-element list, with theint
array as its only member.