1

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
  • 3
    There's a static values method 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 Commented Jun 2, 2020 at 15:38

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.