使用Collections API Shuffle [英] Using Collections API to Shuffle

查看:132
本文介绍了使用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.

这篇关于使用Collections API Shuffle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆