I am just wondering how to pick random values from enum in a different class. For example, I have Person and Victorian as classes and both classes do not have main method. In the Person class, there is enum Profession which takes on “doctor”, “ceo”, “unemployed” and “unknown”, and in the Victorian class, I want to pick random values from this enum. Is it possible?
1 Answer
You can do:
Profession randomValue =
Profession.values()[new Random().nextInt(Profession.values().length)];
If you want to do this more often you should initialize the Random only once:
Random random = new Random();
Profession[] enumValues = Profession.values();
for (int i = 0; i < 100; i++) {
Profession randomValue = enumValues[random.nextInt(enumValues.length)];
System.out.println(randomValue);
}
valuesmethod generated for each enum that returns an array of all the constants, so you can just pick the constant at a random index of that array