Deep mastery of Enum in Java

Source: Internet
Author: User

For something that you want to represent a finite kind of thing in a program, generally we can do it in two ways: public static final String constant, and second, using Enum to represent. In general, the former is simple, but not very good to provide more information, and in Java, the enum is very strong, but also more professional.

1. most C-style enum:

/***/publicenum  datasources {    MASTER0, MASTER1, SLAVE0, SLAVE1, SLAVE2,  SLAVE2}

This is the simplest enum, almost the same as in the C language. Simple and concise But the function is also very weak.

2. Nature of the enum

The essence of enum in Java is a class that inherits Java.lang.Enum . So he's more powerful than the C-style enum. It can also attribute, method, constructor and so on, see an example below:

Importorg.apache.commons.lang.StringUtils;/*** Error Code enumeration*/ Public enumErrorcodeenum {/**System Exceptions*/System_error ("System_error", "System exception"),    /**Invalid parameter*/Illegal_argument ("Illegal_argument", "argument illegal"),    /**Illegal Signature*/Illegal_sign ("Illegal_sign", "illegal signature"),

// ... ...
/**Illegal registration Code*/Illegal_reg_code ("Illegal_reg_code", "Illegal registration code"); /**Enumeration Code*/ PrivateString Code; /**Enumeration Description*/ PrivateString desc; PrivateErrorcodeenum (string code, String desc) { This. Code =Code; This. desc =desc; } PublicString GetCode () {returnCode; } PublicString GetDesc () {returndesc; } /*** Get an enumeration based on an enumerator *@paramCode Enumeration Code *@returnEnumeration*/ Public Static Finalerrorcodeenum Getbycode (String code) {if(Stringutils.isblank (code)) {return NULL; } for(Errorcodeenum item:ErrorCodeEnum.values ()) {if(Stringutils.equals (Item.getcode (), code)) {returnitem; } } return NULL; }}

We seeErrorcodeenumHas attributesString CodeAndString desc, and has a private constructor. The reason is that our enumeration constants need to use the definition of this private constructor:system_error ("System_error", "System Exception") is the private constructor of the invoked enumeration:Private Errorcodeenum (string code, String desc) ; So in factErrorcodeenumEnumeration constants defined in thesystem_error, illegal_argument And so on is actually the equivalentErrorcodeenumBecause they are calledErrorcodeenumGenerated by the private constructor. andErrorcodeenum'sPropertystring code and string desc are defined to better provide more detailed error information. It is also possible to define a variety of other helper methods in the enumeration errorcodeenum.

so the essence of an enumeration is a class that inherits and Java.lang.Enum, and enumeration constants are instances of enumerations . Enumerations can have properties and methods to harden the functionality of enumerations. Enumerations are generally not well understood in Java and generally grasp the nature behind enumerations, so it is no more difficult to understand them.

3. Common methods of enumeration

     Public Static void Main (string[] args) {        System.out.println (System_error.name ());        System.out.println (System_error.ordinal ());        System.out.println (System_error.tostring ());          for (Errorcodeenum e:errorcodeenum.values ()) {            System.out.println (e.name ());            System.out.println (E.getdesc ());        }                System.out.println (ErrorCodeEnum.SYSTEM_ERROR.name ());
System.out.println (errorcodeenum.valueof (Errorcodeenum.class, "illegal_argument"));

String name (): Returns The name of this enum constant, exactly as declared in its enum declaration. Returns the string when the enumeration constant is declared.

int ordinal (): Returns the ordinal position of the declaration of an enumeration constant, like an array's index, starting at 0.

ValueOf (class<t> enumtype, string name): is actually a conversion from a string of enumerated constants to an enumeration constant, equivalent to a factory method.

The name () method is a conversion from an enumeration constant to a string, and ValueOf is a string-to-enumeration constant .

VALUES (): The method is an implicit method, all the constants of a enum type can be obtained by calling the implicit method of this public static T[] values() type . Used to iterate through all the enumeration constants in the enumeration.

4. enum-related data structures: Enummap, enumset Specific reference to JDK documentation.

5. Advantages of enum relative to constants (slightly)

Deep mastery of Enum in Java

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: info-contact@alibabacloud.com 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.