Get enum by its inner field

后端 未结 5 1337
清歌不尽
清歌不尽 2020-11-27 15:48

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         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:51

    You can use a static Map with a static initializer that populates it with the TestEnum values keyed by their number fields.

    Note that findByKey has been made static, and number has also been made final.

    import java.util.*;
    
    public enum TestEnum {
        ONE(1), TWO(2), SIXTY_NINE(69);
    
        private final int number;    
        TestEnum(int number) {
            this.number = number;
        }
    
        private static final Map map;
        static {
            map = new HashMap();
            for (TestEnum v : TestEnum.values()) {
                map.put(v.number, v);
            }
        }
        public static TestEnum findByKey(int i) {
            return map.get(i);
        }
    
        public static void main(String[] args) {
            System.out.println(TestEnum.findByKey(69)); // prints "SIXTY_NINE"
    
            System.out.println(
                TestEnum.values() == TestEnum.values()
            ); // prints "false"
        }
    }
    

    You can now expect findByKey to be a O(1) operation.

    References

    • JLS 8.7 Static initializers
    • JLS 8.9 Enums

    Related questions

    • Static initalizer in Java
    • How to Initialise a static Map in Java

    Note on values()

    The second println statement in the main method is revealing: values() returns a newly allocated array with every invokation! The original O(N) solution could do a little better by only calling values() once and caching the array, but that solution would still be O(N) on average.

提交回复
热议问题