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?
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.