Dienstag, 9. Oktober 2012

Enum in Java with array of string values

Creating enums with string values in Java is quite simple. There are many examples for this on the net:

public enum StrEnum {
    A ("a"), B ("b"), C ("c");
    private final String text;
    StrEnum (String text) { this.text = text; }
    public String toString () { return text; }
}

Those enums can be used in a switch statement and are printable, because they have a string value.

But sometimes it is useful to have the string values of all enums in a string array. This can be done by the use of ordinal(). The following code adds a static string array with all enum values to the class.

private static final String[] array;
static {
    array = new String[StrEnum.values().length];
    for (StrEnum value : StrEnum.values())
        array[value.ordinal()] = value.toString();
}
public static String[] toArray () { return array; }

And this is the a complete example. Try it with javac scratch.java && java scratch:

class scratch
{
    public enum StrEnum {
        A ("a"), B ("b"), C ("c");
        private final String text;
        StrEnum (String text) { this.text = text; }
        public String toString () { return text; }
        private static final String[] array;
        static {
            array = new String[StrEnum.values().length];
            for (StrEnum value : StrEnum.values())
                array[value.ordinal()] = value.toString();
        }
        public static String[] toArray () { return array; }
    }

    public static void main (String[] args)
    {
        for (String str : StrEnum.toArray()) {
            System.out.println (str);
        }
    }
}

Keine Kommentare: