Have enum with inner fields, kind of map.
Now I need to get enum by its 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?
You can use a
static Map<Integer,TestEnum>with astaticinitializer that populates it with theTestEnumvalues keyed by theirnumberfields.Note that
findByKeyhas been madestatic, andnumberhas also been madefinal.You can now expect
findByKeyto be aO(1)operation.References
Related questions
Note on
values()The second
printlnstatement in themainmethod is revealing:values()returns a newly allocated array with every invokation! The originalO(N)solution could do a little better by only callingvalues()once and caching the array, but that solution would still beO(N)on average.