Java1.5 provides a keyword enum that makes it easy to define the type of enumeration you need, for example
- enum Season {
- SPRING, SUMMER, AUTUMN, WINTER
- }
A seasonal enumeration type is defined.
In this case, for season.spring this object, Season.SPRING.name () can get the object's string, which is "spring", and conversely, the object can be obtained by season.valueof ("Spring"), That is season.spring. That is, using the name () method and the ValueOf (string) method makes it easy to convert between an enumerated type object and a string. Of course, assuming that the valueof (string) method is not a valid string for the enumeration type, the IllegalArgumentException exception is thrown.
For enumeration types, the inside of Java is actually a subclass that is converted to java.lang.Enum, which can be observed by "javap-c Season" Command de-compilation. The enum class provides a ordinal () method that returns the ordinal of an enumerated object, such as spring, SUMMER, AUTUMN, Winter, respectively, in this case, the ordinal number is 0, 1, 2, 3. In some cases, we need to use this ordinal, and it is possible to generate the required enumeration object from this ordinal, but the enum does not provide the valueof (int) This scheme, is it impossible to do?
For this problem, you can actually use the values () method of the enumeration type to do it indirectly. The values () method returns an array of enumerated objects, for example, season[], and the array elements are arranged in ordinal order. In the enumeration type that you define, we simply define our own valueof (int) method and return the object of the array subscript object to be able. The code is as follows:
- enum Season {
- SPRING, SUMMER, AUTUMN, WINTER;
- public static Season valueOf (int ordinal) {
- if (ordinal < 0 | | ordinal >= VALUES (). length) {
- throw new indexoutofboundsexception ("Invalid ordinal" c11>);
- }
- return values () [ordinal];
- }
- }
What, it's pretty simple, right?
How to obtain an enumerated constant object from the ordinal value of an enumeration constant in Java