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]

> 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.
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.
> 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.