Get enum by it's inner field
Posted
by zeroed
on Stack Overflow
See other posts from Stack Overflow
or by zeroed
Published on 2010-05-06T09:54:09Z
Indexed on
2010/05/06
9:58 UTC
Read the original article
Hit count: 275
Hi!
Have enum with inner fields, kind of map.
Now I need to get enum by it's inner field.
Wrote this:
package test;
/**
* Test enum to test enum =)
*/
public enum TestEnum {
ONE(1), TWO(2), THREE(3);
private int number;
TestEnum(int number) {
this.number = number;
}
public TestEnum findByKey(int i) {
TestEnum[] testEnums = TestEnum.values();
for (TestEnum testEnum : testEnums) {
if (testEnum.number == i) {
return testEnum;
}
}
return null;
}
}
But it's not very efficient to look up through all enums each time I need to find appropriate instance.
Is there any other way to do the same?
© Stack Overflow or respective owner