How to randomize enum elements? [duplicate]

谁都会走 提交于 2020-01-10 14:12:28

问题


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?


回答1:


Java's enums are actually fully capable Objects. You can add a method to the enum declaration

public enum LightColor {
    Green,
    Yellow,
    Red;

    public static LightColor getRandom() {
        return values()[(int) (Math.random() * values().length)];
    }
}

Which would allow you to use it like this:

LightColor randomLightColor = LightColor.getRandom();



回答2:


LightColor random = LightColor.values()[(int)(Math.random()*(LightColor.values().length))];



回答3:


Use Enum.values() to get all available options and use the Random.nextInt() method specifying the max value. eg:

private static Random numberGenerator = new Random();
public <T> T randomElement(T[] elements)
  return elements[numberGenerator.nextInt(elements.length)];
}

This can then be called as such:

LightColor randomColor = randomElement(LightColor.values());



回答4:


This should be just easy as shown below

LightColor[] values = LightColor.values();
LightColor value = values[(int) (Math.random() * 3)];



回答5:


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




回答6:


So reading Kowser's answer, I came up with something here. Given an enum ChatColor containing different colors, you could do the following:

private ChatColor getRandomColor() {
    ChatColor randomColor = ChatColor.values()[random.nextInt(ChatColor
            .values().length - 1)];
    ChatColor[] blacklist = { ChatColor.BOLD, ChatColor.ITALIC,
            ChatColor.MAGIC, ChatColor.RESET, ChatColor.STRIKETHROUGH,
            ChatColor.UNDERLINE };
    while (Arrays.asList(blacklist).contains(randomColor)) {
        randomColor = ChatColor.values()[random
                .nextInt(ChatColor.values().length)];
    }
    return randomColor;
}

and even have a blacklist.



来源:https://stackoverflow.com/questions/8114174/how-to-randomize-enum-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!