【发布时间】:2015-05-18 04:57:08
【问题描述】:
我有一个像这样的 EnumSet,所以要随机播放元素,我需要将其转换为 List。
EnumSet<Fruit> otherFruits = EnumSet.complementOf(CURRENT_FRUIT);
下面是我的代码,我在其中进行洗牌并将其添加到原始result 列表中:
private static List<Fruits> getFruits() {
EnumSet<Fruits> local = EnumSet.of(CURRENT_FRUIT);
// first element in the list will always be the local fruit so using LinkedList
List<Fruits> result = new LinkedList<Fruits>(local);
// I just want to shuffle remoteFruits only
EnumSet<Fruit> otherFruits = EnumSet.complementOf(CURRENT_FRUIT);
List<Fruits> remoteFruits = new ArrayList<Fruits>(otherFruits);
Collections.shuffle(remoteFruits, new Random(System.nanoTime()));
result.addAll(remoteFruits);
return result;
}
到目前为止,我在上面的代码中使用了两个列表,然后将remoteFruits 列表的所有元素添加到result 列表中。有没有办法在一个列表中完成所有这些事情?我只想随机播放otherFruits 元素。
这里有优化的机会吗?
【问题讨论】:
-
无关:你应该使用
new Random()而不是new Random(System.nanoTime())。 -
你可以在
remoteFruits的开头添加CURRENT_FRUIT洗牌后。 -
@immibis
new Random()和new Random(System.nanoTime())有什么区别吗?为什么你建议第一个? -
那么,你为什么要使用比它可能的随机性更小的种子呢? (而且:如果他们想出一种更随机的生成种子的方法,那么如果您使用
new Random(),您将免费获得改进) -
无关:你应该使用
Collections.shuffle(remoteFruits);而不使用任何Random参数(它已经为你使用了一个 Random 实例,并且这样做更有效,因为它缓存了它。
标签: java list collections enums set