Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for a Java enum to have "missing" integer values for its elements?

Tags:

java

enums

For example, I have two elements in an enum. I would like the first to be represented by the integer value 0 and the string A, but the second to be represented by the integer value of 2 and the string "B" (as opposed to 1). Is this possible?

Currently, my enum is declared as this:

public enum Constants {
    ZERO("Zero");
    TWO("Two");
}

If I were to get the integer values of ZERO and TWO, I would currently get 0 and 1, respectively. However, I would like to get 0 and 2.

like image 933
Thomas Owens Avatar asked Nov 29 '22 06:11

Thomas Owens


2 Answers

Define an appropriately named integer field for your enum and initialize it to whatever value suits you best. The internal ordinal of enums is not meant to carry an meaning.

like image 37
Michael Borgwardt Avatar answered Dec 04 '22 18:12

Michael Borgwardt


I assume you are referring to a way to make the ordinal of the Enum return a user-defined value. If this is the case, no.

If you want to return a specific value, implement (e.g. getValue()) and pass it in the Enum constructor.

For example:

public enum Constants {
    ZERO("Zero",0),
    TWO("Two",2);

    final private String label;
    final private int value;

    Constants(String label, int value) {
        this.label = label;
        this.value= value;
    }

    public int getValue() {
        return value;
    }

    public String getLabel() {
        return label;
    }
}
like image 191
Rich Seller Avatar answered Dec 04 '22 16:12

Rich Seller