Get index of enum from string?

前端 未结 5 1352
暗喜
暗喜 2021-01-07 17:55

I have a string value, I also have an array of strings and an enum containing the range also. To get the index of the string in the array, from the value supplied I write th

相关标签:
5条回答
  • 2021-01-07 18:11

    Try this simple solution:

    Fruit.values()[index]
    
    0 讨论(0)
  • 2021-01-07 18:12

    If you want to retrieve the index, you can use ordinal. If you want to assign some specific value to String, you may define your own method to retrieve it.

     enum DAY
     {
      MONDAY(10),
      TUESDAY(20);
      int value;
      DAY(int x)
      {
       this.value = x;
      }
      public int getValue()
      {
        return value;
       }
    

    Now value and ordinal can be retrieved as :

        for(DAY s : DAY.values() )
        {
            System.out.println(s.ordinal());
            System.out.println(s.getValue());
        }
    
    0 讨论(0)
  • 2021-01-07 18:17

    Not sure if I understand you correctly but based on question title you may be looking for

    YourEnum.valueOf("VALUE").ordinal();
    
    1. YourEnum.valueOf("VALUE") returns enum value with name "VALUE"
    2. each enum value knows its position (indexed from zero) which we can get by calling ordinal() method on it.
    0 讨论(0)
  • 2021-01-07 18:24

    The following logic will also work.

    If you want to check and you know the fruitname already don't use for loop go with the approach mentioned by Pshemo

    for (Fruit aFruit : aFruits)
               if (aFruit.name().equals(aName))
                   return aFruit.ordinal();
    
    0 讨论(0)
  • 2021-01-07 18:33

    I might not understand you question, but the same code works for enums too:

    int index = Arrays.asList(YourEnum.values()).indexOf(YourEnum.ENUM_ITEM);
    

    Or you can get:

    int index = YourEnum.valueOf("ENUM_ITEM").ordinal();
    
    0 讨论(0)
提交回复
热议问题