How to get Enum Value from index in Java?

前端 未结 4 1523
我寻月下人不归
我寻月下人不归 2020-12-07 13:09

I have an enum in Java:

public enum Months
{
    JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}

I want to access enum values

4条回答
  •  [愿得一人]
    2020-12-07 13:34

    I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

    The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

    public enum Example {
    
        UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");
    
        private static HashMap enumById = new HashMap<>();
        static {
            Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
        }
    
        public static Example getById(int id) {
            return enumById.getOrDefault(id, UNKNOWN);
        }
    
        private int id;
        private String description;
    
        private Example(int id, String description) {
            this.id = id;
            this.description= description;
        }
    
        public String getDescription() {
            return description;
        }
    
        public int getId() {
            return id;
        }
    }
    

    If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

    public static Example getById(int id) {
            return enumById.get(id);
    }
    

提交回复
热议问题