如何随机化枚举元素?
假设您有一个包含一些元素的enum
public enum LightColor {
RED, YELLOW, GREEN
}
,并且想从中随机选择任何颜色。
我将颜色放入 a
public List<LightColor> lightColorChoices = new ArrayList<LightColor>();
lightColorChoices.add(LightColor.GREEN);
lightColorChoices.add(LightColor.YELLOW);
lightColorChoices.add(LightColor.RED);
然后选择一个随机颜色,例如:
this.lightColor = lightColorChoices.get((int) (Math.random() * 3));
所有这些(虽然工作正常)似乎不必要地复杂。有没有更简单的方法来选择随机枚举元素?
Say you have an enum
with some elements
public enum LightColor {
RED, YELLOW, GREEN
}
And would like to randomly pick any color from it.
I put colors into a
public List<LightColor> lightColorChoices = new ArrayList<LightColor>();
lightColorChoices.add(LightColor.GREEN);
lightColorChoices.add(LightColor.YELLOW);
lightColorChoices.add(LightColor.RED);
And then picked a random color like:
this.lightColor = lightColorChoices.get((int) (Math.random() * 3));
All of this (while working fine) seems needlessly complicated. Is there a simplier way to pick a random enum element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Java 的枚举实际上是功能齐全的对象。您可以将一个方法添加到
enum
声明中,这将允许您像这样使用它:
Java's enums are actually fully capable Objects. You can add a method to the
enum
declarationWhich would allow you to use it like this:
使用 Enum.values() 获取所有可用选项并使用Random.nextInt() 方法指定最大限度 价值。例如:
然后可以这样调用:
Use Enum.values() to get all available options and use the Random.nextInt() method specifying the max value. eg:
This can then be called as such:
这应该很简单,如下所示
This should be just easy as shown below
您可以将一个整数 id 与每个枚举颜色相关联,并使用 valueOf(int id) 方法返回相应的颜色。这将帮助您摆脱列表..
Tiberiu
You could associate an integer id to each enum color, and have a valueOf(int id) method that returns the corresponding color. This will help you get rid of the list..
Tiberiu
因此,阅读 Kowser 的答案后,我想到了一些东西。
给定一个包含不同颜色的枚举 ChatColor,您可以执行以下操作:
甚至可以有一个黑名单。
So reading Kowser's answer, I came up with something here.
Given an enum ChatColor containing different colors, you could do the following:
and even have a blacklist.