Getting all names in an enum as a String[]

前端 未结 21 1459
执笔经年
执笔经年 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:46

    Just a thought: maybe you don't need to create a method to return the values of the enum as an array of strings.

    Why do you need the array of strings? Maybe you only need to convert the values when you use them, if you ever need to do that.

    Examples:

    for (State value:values()) {
        System.out.println(value); // Just print it.
    }
    

    for (State value:values()) {
        String x = value.toString(); // Just iterate and do something with x.
    }
    

    // If you just need to print the values:
    System.out.println(Arrays.toString(State.values()));
    

提交回复
热议问题