How to get Enum Value from index in Java?

前端 未结 4 1525
我寻月下人不归
我寻月下人不归 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:28

    I just tried the same and came up with following solution:

    public enum Countries {
        TEXAS,
        FLORIDA,
        OKLAHOMA,
        KENTUCKY;
    
        private static Countries[] list = Countries.values();
    
        public static Countries getCountry(int i) {
            return list[i];
        }
    
        public static int listGetLastIndex() {
            return list.length - 1;
        }
    }
    

    The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:

    public static String getCountry(int i) {
        return list[(i - 1)];
    }
    
    public static int listGetLastIndex() {
        return list.length;
    }
    

    Inside my Main I get the needed countries-object with

    public static void main(String[] args) {
       int i = Countries.listGetLastIndex();
       Countries currCountry = Countries.getCountry(i);
    }
    

    which sets currCountry to the last country, in this case Countries.KENTUCKY.

    Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.

提交回复
热议问题