Conveniently map between enum and int / String

前端 未结 18 1714
陌清茗
陌清茗 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:17

    Both the .ordinal() and values()[i] are unstable since they are dependent to the order of enums. Thus if you change the order of enums or add/delete some your program would break.

    Here is a simple yet effective method to map between enum and int.

    public enum Action {
        ROTATE_RIGHT(0), ROTATE_LEFT(1), RIGHT(2), LEFT(3), UP(4), DOWN(5);
    
        public final int id;
        Action(int id) {
            this.id = id;
        }
    
        public static Action get(int id){
            for (Action a: Action.values()) {
                if (a.id == id)
                    return a;
            }
            throw new IllegalArgumentException("Invalid id");
        }
    }
    

    Applying it for strings shouldn't be difficult.

    0 讨论(0)
  • 2020-11-28 01:18

    You could perhaps use something like

    interface EnumWithId {
        public int getId();
    
    }
    
    
    enum Foo implements EnumWithId {
    
       ...
    }
    

    That would reduce the need for reflection in your utility class.

    0 讨论(0)
  • 2020-11-28 01:18

    given:

    public enum BonusType { MONTHLY(0), YEARLY(1), ONE_OFF(2) }

    BonusType bonus = YEARLY;

    System.out.println(bonus.Ordinal() + ":" + bonus)

    Output: 1:YEARLY

    0 讨论(0)
  • 2020-11-28 01:19

    I'm not sure if it's the same in Java, but enum types in C are automatically mapped to integers as well so you can use either the type or integer to access it. Have you tried simply accessing it with integer yet?

    0 讨论(0)
  • 2020-11-28 01:20

    For the sake of completeness, here is a generic approach to retrieve enum values by index from any enum type. My intention was to make the method look and feel like Enum.valueOf(Class, String). Fyi, i copied this method from here.

    Index related issues (already discussed in depth here) still apply.

    /**
     * Returns the {@link Enum} instance for a given ordinal.
     * This method is the index based alternative
     * to {@link Enum#valueOf(Class, String)}, which
     * requires the name of an instance.
     * 
     * @param <E> the enum type
     * @param type the enum class object
     * @param ordinal the index of the enum instance
     * @throws IndexOutOfBoundsException if ordinal < 0 || ordinal >= enums.length
     * @return the enum instance with the given ordinal
     */
    public static <E extends Enum<E>> E valueOf(Class<E> type, int ordinal) {
        Preconditions.checkNotNull(type, "Type");
        final E[] enums = type.getEnumConstants();
        Preconditions.checkElementIndex(ordinal, enums.length, "ordinal");
        return enums[ordinal];
    }
    
    0 讨论(0)
  • 2020-11-28 01:25
    Int -->String :
    
    public enum Country {
    
        US("US",0),
        UK("UK",2),
        DE("DE",1);
    
    
        private static Map<Integer, String> 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<Integer, String>();
                for (Country s : values()) {
                    domainToCountryMapping.put(s.domain, s.country);
                }
            }
    
    0 讨论(0)
提交回复
热议问题