How to get an enumerated constant object from the ordinal value of an enumeration constant in Java

Source: Internet
Author: User

Java1.5 provides a keyword enum that makes it easy to define the type of enumeration you need, for example
    1. enum Season {
    3. }
A seasonal enumeration type is defined.

In this case, for season.spring this object, () 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:
  1. enum Season {
  3. public static Season valueOf (int ordinal) {
  4. if (ordinal < 0 | | ordinal >= VALUES (). length) {
  5. throw new indexoutofboundsexception ("Invalid ordinal" c11>);
  6. }
  7. return values () [ordinal];
  8. }
  9. }
What, it's pretty simple, right?
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.