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; } ... }
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.
each enum value knows its position (indexed from zero) which we can get by calling ordinal() method on it.
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.)
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.
Not sure if I understand you correctly but based on question title you may be looking for
YourEnum.valueOf("VALUE").ordinal();
YourEnum.valueOf("VALUE")
returns enum value with name "VALUE"
ordinal()
method on it.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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With