tags:

views:

642

answers:

4

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.

+11  A: 

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;
    }
}
Rich Seller
From the JavaDocs: "Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero)." They are indeed numberd 0 - number of elements.
amischiefr
However, by not using the ordinal() method and by passing a value into the constructor, I can hide the true ordinal value from users and use whatever I want.
Thomas Owens
You should make label and value final.
Steve Kuo
@Steve, good point
Rich Seller
+2  A: 

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.

Michael Borgwardt
+2  A: 

try something like this:

public enum MyEnum {

A(1), B(2), C(3);

int myOrdinal;

private MyEnum(int myOrdinal) {
    this.myOrdinal = myOrdinal;
}

public int getMyOrdinal() {
    return myOrdinal;
}

If you rely on the internal numbering of the enum, then ordering matters and even different jvm's could handle it differently, which would lead to unpredictable behaviour (unless it is specified in the "enum jsr-161", haven't read it...).

I saw an implementation that relied on the inner ordinal, it was used for the ordering in a web dropdown box. It produced funny bugs once someone had kindly "clean up" the enum values..

raoulsson
+1  A: 

You want to pass an integer in the constructor, then use String input = ... int inputAsInt = Constants.valueOf(input.toUpperCase()).getValue();

Something like

public enum Constants{
 ZERO(0),
 TWO(1);
 private final int value;
 public Numbers(int value){
  this.value = value;
 }

 public int getValue(){
  return this.value;
 }
}
Hameltime