Paul Paul - 3 months ago 7x
Java Question

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:


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;


Not sure if I understand you correctly but maybe you are looking for

  • YourEnum.valueOf("VALUE") returns enum value with name VALUE
  • and each enum value knows its position (indexed from zero) which we can see using ordinal() method.