What are enums and why are they useful?

后端 未结 27 1354
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  一生所求
    2020-11-22 07:16

    I would use enums as a useful mapping instrument, avoiding multiple if-else provided that some methods are implemented.

    public enum Mapping {
    
        ONE("1"),
        TWO("2");
    
        private String label;
    
        private Mapping(String label){
            this.label = label;
        }
    
        public static Mapping by(String label) {
    
            for(Mapping m: values() {
                if(m.label.equals(label)) return m;
            }
    
            return null;
        }
    
    }
    

    So the method by(String label) allows you to get the Enumerated value by non-enumerated. Further, one can invent mapping between 2 enums. Could also try '1 to many' or 'many to many' in addition to 'one to one' default relation

    In the end, enum is a Java class. So you can have main method inside it, which might be useful when needing to do some mapping operations on args right away.

提交回复
热议问题