Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of enum from string?

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 this:

Arrays.asList(myClass.BAUD_RATES).indexOf(username) 

How do I do this for an enum? Can I use ordinal? Or do i have to make my own method?

The method might go like:

public enum Fruit {    ...    static public boolean isMember(String aName) {        Fruit[] aFruits = Fruit.values();        for (Fruit aFruit : aFruits)            if (aFruit.fruitname.equals(aName))                return aFruit;        return false;    }    ... } 
like image 290
Paul Avatar asked Mar 15 '13 15:03

Paul


People also ask

How do you find the index of an enum?

Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.

Does enum have index?

each enum value knows its position (indexed from zero) which we can get by calling ordinal() method on it.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Can a enum extend another class?

Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java. lang. Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.


2 Answers

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.
like image 126
Pshemo Avatar answered Sep 18 '22 13:09

Pshemo


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(); 
like image 43
Alban Dericbourg Avatar answered Sep 18 '22 13:09

Alban Dericbourg