使用 Collections API 进行随机播放

发布于 2024-07-07 02:12:27 字数 257 浏览 9 评论 0原文

我感到非常沮丧,因为我似乎无法弄清楚为什么集合洗牌无法正常工作。

假设我正在尝试对随机化器数组进行洗牌。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽清梦 2024-07-14 02:12:42

克里斯的回答是正确的。

正如我在对 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.

夜血缘 2024-07-14 02:12:39

Arrays.asList 不能与基元数组一起使用。 请使用此替代:

Integer[] randomizer = new Integer[] {200,300,212,111,6,2332}; 
Collections.shuffle(Arrays.asList(randomizer));

相同的规则适用于集合框架中的大多数类,因为您不能使用原始类型。

原始代码(使用 int[])编译得很好,但由于可变参数方法 asList 的行为而没有按预期工作:它只生成一个元素列表,int 数组作为其唯一成员。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文