Question
How can I randomly select a value from an enum in Java?
public enum Letter {
A,
B,
C
}
private Letter randomLetter() {
return Letter.values()[new Random().nextInt(Letter.values().length)];
}
Answer
Selecting a random value from an enum in Java is a common task that ensures a fair distribution of values. The method below demonstrates how to accomplish this efficiently using Java's built-in methods.
import java.util.Random;
public enum Letter {
A, B, C;
}
public class EnumRandomPicker {
private static final Random random = new Random();
public static Letter randomLetter() {
return Letter.values()[random.nextInt(Letter.values().length)];
}
}
Solutions
- Use `Random` to generate an index based on the length of the enum values.
- Access the enum values using `Letter.values()`.
- Return the randomly selected enum value.
Common Mistakes
Mistake: Recreating the Random object multiple times leads to poor randomness.
Solution: Instantiate Random once and reuse it throughout the class.
Mistake: Using a hard-coded index or array length can cause issues with missing enum values.
Solution: Always use `Letter.values().length` to ensure robustness.
Helpers
- Java random enum selection
- random value from enum Java
- Enum in Java
- Java random picker from enum
- select random enum value