Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java custom enum value to enum

Tags:

java

enums

I have enum like this

public enum Sizes {
    Normal(232), Large(455);

    private final int _value;

    Sizes(int value) {
        _value = value;
    }

    public int Value() {
        return _value;
    }
}

Now I can call Sizes.Normal.Value() to get integer value, but how do I convert integer value back to enum?

What I do now is:

public Sizes ToSize(int value) {
    for (Sizes size : Sizes.values()) {
        if (size.Value() == value)
            return size;
    }
    return null;
}

But that's only way to do that? That's how Java works?

like image 479
xmen Avatar asked May 19 '12 02:05

xmen


2 Answers

Yes that's how it's done, generally by adding a static method to the enum. Think about it; you could have 10 fields on the enum. Do you expect Java to set up lookups for all of them?

The point here is that Java enums don't have a 'value'. They have identity and an ordinal, plus whatever you add for yourself. This is just different from C#, which follows C++ in having an arbitrary integer value instead.

like image 106
bmargulies Avatar answered Oct 19 '22 22:10

bmargulies


It's been a while since I last worked with Java, but if I recall correctly, there's no relation between your _value field and the enum's ordinal. AFAIK you could have two entries with the same _value, for instance. As @bmargulies pointed out, you could have many fields in the enum, and nothing constrain you to use distinct values for each (or all) of them.

See also this related question. Apparently, you can't directly set the ordinal of your entries.

like image 44
mgibsonbr Avatar answered Oct 19 '22 23:10

mgibsonbr