7

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
xmen
  • 1,947
  • 2
  • 25
  • 47
  • 1
    possible duplicate of [Java enum reverse look-up best practice](http://stackoverflow.com/questions/5316311/java-enum-reverse-look-up-best-practice) – bmargulies May 19 '12 at 02:27

2 Answers2

8

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.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • 2
    I tried to put a static HashMap into his enum, but it appears that you aren't allowed to fill it from within the enum constructor. 1+ – Hovercraft Full Of Eels May 19 '12 at 02:22
  • well I still prefer how C# handles enums. Its much faster. Enum suppose to be a integer Identifier, not the entire class :) – xmen May 19 '12 at 02:23
  • You might need to initialize it in a static block. static private HashMap map = new HashMap; and then do puts in the ctor? – bmargulies May 19 '12 at 02:24
  • 1
    @Hovercraft Full Of Eels: I tried too, and it says Cannot refer to the static enum field Sizes.ValuesHolder within an initializer – xmen May 19 '12 at 02:24
  • 3
    See http://stackoverflow.com/questions/5316311/java-enum-reverse-look-up-best-practice. – bmargulies May 19 '12 at 02:27
  • @bmargulies: wow thats exactly what I just did, using static constructor. Thanks – xmen May 19 '12 at 02:35
1

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.

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • thats why I asked, I was thinking there could be built-in support in java like C# but I have to write everything. Its like working in C++ lol – xmen May 19 '12 at 02:29