Conveniently map between enum and int / String

前端 未结 18 1815
陌清茗
陌清茗 2020-11-28 01:07

When working with variables/parameters that can only take a finite number of values, I try to always use Java\'s enum, as in

public enum BonusT         


        
18条回答
  •  一生所求
    2020-11-28 01:25

    Int -->String :
    
    public enum Country {
    
        US("US",0),
        UK("UK",2),
        DE("DE",1);
    
    
        private static Map domainToCountryMapping; 
        private String country;
        private int domain;
    
        private Country(String country,int domain){
            this.country=country.toUpperCase();
            this.domain=domain;
        }
    
        public String getCountry(){
            return country;
        }
    
    
        public static String getCountry(String domain) {
            if (domainToCountryMapping == null) {
                initMapping();
            }
    
            if(domainToCountryMapping.get(domain)!=null){
                return domainToCountryMapping.get(domain);
            }else{
                return "US";
            }
    
        }
    
         private static void initMapping() {
             domainToCountryMapping = new HashMap();
                for (Country s : values()) {
                    domainToCountryMapping.put(s.domain, s.country);
                }
            }
    

提交回复
热议问题