Getting all names in an enum as a String[]

前端 未结 21 1384
执笔经年
执笔经年 2020-12-01 03:50

What\'s the easiest and/or shortest way possible to get the names of enum elements as an array of Strings?

What I mean by this is that if, for example,

21条回答
  •  执笔经年
    2020-12-01 04:48

    Create a String[] array for the names and call the static values() method which returns all the enum values, then iterate over the values and populate the names array.

    public static String[] names() {
        State[] states = values();
        String[] names = new String[states.length];
    
        for (int i = 0; i < states.length; i++) {
            names[i] = states[i].name();
        }
    
        return names;
    }
    

提交回复
热议问题