1

Is it possible to get an enum with its ordinal?

enum SimpleJackCards {
    As(11), König(10), Dame(10), Bube(10), Zehn(10), Neun(9), Acht(8),
    Sieben(7), Sechs(6), Fünf(5), Vier(4), Drei(3),Zwei(2), Yolly (1);
    private int value;
    SimpleJackCards(int val) {
        value = val;
    }
    int getValue (){
        return value;
    }
}

For example

I want to write a method that gives me a random card ... I would randomize an integer.

And want to get that enum with the generated ordinal number.

i.e.: ordinal value 0 would be enum As with value 11.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • Check this out: https://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type – bad_coder Dec 29 '19 at 11:31
  • 3
    Does this answer your question? [Convert from enum ordinal to enum type](https://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type) – bad_coder Dec 29 '19 at 11:31
  • 2
    Little note: `enum` constants should be written in UPPER_SNAKE_CASE. – MC Emperor Dec 29 '19 at 12:53

2 Answers2

7

You could simply access the array returned by values() using the randomly generated number as index (which represents the ordinal):

// i.e.: if someRandomNumber = 0, then randomCard will be "As"
SimpleJackCards randomCard = SimpleJackCards.values()[someRandomNumber];
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
0

There isn't a method on Enum to retrieve it by the ordinal. You have to do it yourself.

public static SimpleJackCards getByOrdinal(int ordinal) {
    return Arrays.stream(SimpleJackCards.values())
            .filter(e -> e.ordinal() == ordinal)
            .findFirst()
            .orElseThrow(() -> new RuntimeException("Invalid ordinal"));
}

If you don't want to loop over the enum constants each time, you can construct a map, mapping between the ordinal and the enum constant.

private static final Map<Integer, SimpleJackCards> ORDINAL_TO_ENUM;

static {
    ORDINAL_TO_ENUM = Arrays.stream(SimpleJackCards.values())
                .collect(Collectors.toMap(Enum::ordinal, Function.identity()));
}

public static SimpleJackCards getByOrdinal2(int ordinal) {
      return ORDINAL_TO_ENUM.get(ordinal); //returns null if passed an invalid ordinal
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79