xmen
xmen

Reputation: 1967

Java custom enum value to enum

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?

Upvotes: 7

Views: 14667

Answers (2)

bmargulies
bmargulies

Reputation: 100013

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.

Upvotes: 8

mgibsonbr
mgibsonbr

Reputation: 22007

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.

Upvotes: 1

Related Questions