Java:从枚举中选择一个随机值? [英] Java: Pick a random value from an enum?
本文介绍了Java:从枚举中选择一个随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的枚举:
public enum Letter {
A,
B,
C,
//...
}
什么是随机选择一个最好的方法?它不需要生产质量防弹,但相当均匀的分布将是很好的。
What is the best way to pick one randomly? It doesn't need to be production quality bulletproof, but a fairly even distribution would be nice.
我可以做这样的事情
private Letter randomLetter() {
int pick = new Random().nextInt(Letter.values().length);
return Letter.values()[pick];
}
但是有更好的方法吗?我觉得这是以前解决的东西。
But is there a better way? I feel like this is something that's been solved before.
推荐答案
我建议的唯一的事情是缓存<$ c的结果$ c> values()因为每个调用都复制一个数组。另外,不要每次都创建一个 Random
。保持一个除了你在做什么是好的。所以:
The only thing I would suggest is caching the result of values()
because each call copies an array. Also, don't create a Random
every time. Keep one. Other than that what you're doing is fine. So:
public enum Letter {
A,
B,
C,
//...
private static final List<Letter> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Letter randomLetter() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
这篇关于Java:从枚举中选择一个随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文