Java Data Type How to - Get a random value from an enum








Question

We would like to know how to get a random value from an enum.

Answer

import java.util.Random;
//from  www  . ja  v a 2s  . co m
enum Season {
  WINTER, SPRING, SUMMER, FALL
}

class RandomEnum<E extends Enum<Season>> {
  Random RND = new Random();
  E[] values;

  public RandomEnum(Class<E> token) {
    values = token.getEnumConstants();
  }

  public E random() {
    return values[RND.nextInt(values.length)];
  }
}

public class Main {
  public static void main(String[] args) {
    RandomEnum<Season> r = new RandomEnum<Season>(Season.class);
    System.out.println(r.random());
  }
}

The code above generates the following result.