Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Getting an array of ENUM elements

Tags:

java

arrays

enums

Is there a better way of creating arrays from elements of an enum:

    public static enum LOGICAL {
        AND ("&", "AND"),
        OR ("||", "OR");

        public final String symbol;
        public final String label;

        LOGICAL(String symbol, String label) {
            this.symbol=symbol;
            this.label=label;
        }
    }

    public static final String[] LOGICAL_NAMES = new String[LOGICAL.values().length];
    static{
        for(int i=0; i<LOGICAL.values().length; i++)
            LOGICAL_NAMES[i]=LOGICAL.values()[i].symbol;
    }

    public static final String[] LOGICAL_LABELS = new String[LOGICAL.values().length];
    static{
        for(int i=0; i<LOGICAL.values().length; i++)
            LOGICAL_LABELS[i]=LOGICAL.values()[i].label;
    }
like image 865
marcolopes Avatar asked May 28 '11 07:05

marcolopes


People also ask

Can you have an array of enums in Java?

You can iterate through an enum to access its values. The static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values.

Can you have an ArrayList of enums?

You can create a list that holds enum instances just like you would create a list that holds any other kind of objects: ? List<ExampleEnum> list = new ArrayList<ExampleEnum>(); list.

Can enums be arrays?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.


1 Answers

Personally I wouldn't expose them as an array, whose contents can be changed by anyone. I'd probably use an unmodifiable list instead - and probably expose that via a property rather than as a field. The initialization would be something like this:

private static final List<String> labels;
private static final List<String> values;

static
{
    List<String> mutableLabels = new ArrayList<String>();
    List<String> mutableValues = new ArrayList<String>();
    for (LOGICAL x : LOGICAL.values())
    {
         mutableLabels.add(x.label);
         mutableValues.add(x.value);
    }
    labels = Collections.unmodifiableList(mutableLabels);
    values = Collections.unmodifiableList(mutableValues);
}

(If you're already using Guava you might even want to use ImmutableList instead, and expose the collections that way to make it clear that they are immutable.)

like image 115
Jon Skeet Avatar answered Sep 29 '22 08:09

Jon Skeet