从枚举中选择一个随机值?

2022-08-31 06:12:17

如果我有这样的枚举:

public enum Letter {
    A,
    B,
    C,
    //...
}

随机选择一个的最佳方法是什么?它不需要是生产质量的防弹,但相当均匀的分布会很好。

我可以做这样的事情

private Letter randomLetter() {
    int pick = new Random().nextInt(Letter.values().length);
    return Letter.values()[pick];
}

但是有更好的方法吗?我觉得这是以前已经解决的问题。


答案 1

我唯一建议的是缓存结果,因为每个调用都会复制一个数组。另外,不要每次都创建 a。保留一个。除此之外,你正在做的事情很好。所以:values()Random

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));
  }
}

答案 2

对于所有随机枚举,只需一个方法:

    public static <T extends Enum<?>> T randomEnum(Class<T> clazz){
        int x = random.nextInt(clazz.getEnumConstants().length);
        return clazz.getEnumConstants()[x];
    }

您将使用:

randomEnum(MyEnum.class);

我也更喜欢使用SecureRandom作为:

private static final SecureRandom random = new SecureRandom();

推荐