Efficiently retrieve an element of an enum without throwing an IllegalArgum

Given an enum like

enum MyEnum{"ALPHA","BRAVO","CHARLIE"} ;

I'd like to retrieve an element by name, but return null if it's not defined in the enum, rather than throwing a runtime exception like the valueOf method does. The best approach I've found so far is

MyEnum foo =null ;

for (MyEnum next: MyEnum.values()){

if(next.toString().equals("DELTA")){

foo = next ;

}

}

//would rather use something like MyEnum foo = MyEnum.valueOf("DELTA") ;

This seems like a common enough operation, and something that could be optimized by knowing the underlying structure of an enum, that I wanted to be sure that no better method existed.

[1122 byte] By [Telosa] at [2007-11-26 16:00:56]
# 1

> Given an enum like

>

> > enum MyEnum {"ALPHA", "BRAVO", "CHARLIE"} ;

>

>

> I'd like to retrieve an element by name, but return

> null if it's not defined in the enum,

Why?

If you're using an enum, you should know the values and only pass in a name you know to be legal. If you do otherwise, it's a bug in your code and it's correct that an unchecked exception be thrown.

Either catch the exception or check ahead of time whether values() contans it.

jverda at 2007-7-8 22:22:26 > top of Java-index,Java Essentials,Java Programming...
# 2
I'm certainly not adverse to checking ahead as you suggest, but as far as I can tell from the API, I'd have to do essentially the same thing as I originally posted, i.e. sequentially search the enum for an element whose name matches my value.
Telosa at 2007-7-8 22:22:26 > top of Java-index,Java Essentials,Java Programming...
# 3

> I'm certainly not adverse to checking ahead as you

> suggest, but as far as I can tell from the API, I'd

> have to do essentially the same thing as I originally

> posted, i.e. sequentially search the enum for an

> element whose name matches my value.

Yup. You could call Arrays.asList, and then call list.contains. Slightly simpler, more compact code than a loop. That will just do the same sequential search, but for the number of elements you're likely to have in an enum, it will be fast.

jverda at 2007-7-8 22:22:26 > top of Java-index,Java Essentials,Java Programming...
# 4
Although, if I really wanted "invalid name" to map to null (which I generally wouldn't here), I'd probably just catch the exception.
jverda at 2007-7-8 22:22:26 > top of Java-index,Java Essentials,Java Programming...
# 5
If sequential searching is your problem, do a one-off linear scan setting up a HashMap from name to value.
YAT_Archivista at 2007-7-8 22:22:26 > top of Java-index,Java Essentials,Java Programming...