Custom enum Java value for listing

I have listed how it is

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 the integer value, but how to convert the integer value back to enum?

Now I do the following:

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

But is this the only way to do this? What does java work?

+7
source share
2 answers

Yes, how is this done, usually adding a static method to the enumeration. I think about it; You can have 10 fields in listing. Do you expect Java to customize the search for all of them?

The point is that Java enumerations do not matter. They have a personality and an ordinal, plus what you add for yourself. This is just different from C #, which follows C ++ in the presence of an arbitrary integer value.

+8
source

Some time has passed since the last time I worked with Java, but if I remember correctly, there is no connection between your _value field and the enum serial number. AFAIK you could have two entries with the same _value , for example. As @bmargulies pointed out, you can have many fields in an enumeration, and nothing prevents you from using different values ​​for each (or all) of them.

See also this related question . Apparently, you cannot directly set the sequence number of your entries.

+1
source

All Articles