Java basics-enumeration

Source: Internet
Author: User

Objective:

When I first learned object-oriented programming, the deepest word I remember was "all things are objects." So I have been adhering to the idea of learning java, until the enumeration (enum), looking at its rather strange syntax ... I've been thinking, What the hell is this tm??? At that time learning oop is also a kind of interface what the whole is a bit reeling, so the small details Ignored. Later to the company work slowly and need to use the enumeration, look at it a mysterious look I still decided to have a good deep digging! The following links are the blogs that are referenced in understanding Enumerations. If you find this article has errors or knowledge omission welcome in the comments middle finger positive!

  decompile those things (ii)-anti-compilation of enumerations :http://blog.csdn.net/gaohuanjie/article/details/18140279

   The difference between a Java enumeration and a constant class : http://blog.csdn.net/tanqian351/article/details/53736628

directory:

1) History

2) Syntax parsing

3) benefits of enumerations and differences from constant classes

4) enumeration of common methods

1. history:

Enumeration is a new feature of the JDK1.5 version (generics, for-each, etc., which are now widely used by JDK1.5), and the JDK1.6 after the switch statement supports enumeration Types.

2. Syntax parsing of enumerations:

1. Most simple version

public enum Colorenum {red,blue,green}

Source code obtained by tool parsing class (tool reference link Above)

 public Final classColorenumextendsenum{//returns a copy of the array that stores the enumeration instance. The values () method is typically used in a foreach loop to iterate through enumeration Constants.      public Staticcolorenum[] values () {return(colorenum[]) $VALUES. Clone (); } //get instances by instance name  public Staticcolorenum valueOf (String s) {return(colorenum) enum.valueof (colorenum, s); }    //Private constructor method, where the constructor of the parent class is called, where the parameter s corresponds to the constant name, and the parameter I represents an order of the enumeration (this order corresponds to the declaration order of the enumeration and is used for the Oridinal () method to return the order Value)    PrivateColorenum (String s,intI) {Super(s, i); }    //the Enumeration We define here declares a constant object reference of three colorenum, and the object is instantiated in static block     public Static FinalColorenum RED;  public Static FinalColorenum BLUE;  public Static FinalColorenum GREEN; //to store all instances of an enumeration in an array    Private Static FinalColorenum $VALUES []; Static{RED=NewColorenum ("RED", 0); BLUE=NewColorenum ("BLUE", 1); GREEN=NewColorenum ("GREEN", 2); //to store all instances of an enumeration in an array$VALUES = (Newcolorenum[] {RED, BLUE, GREEN}); }}

2. Now we add our own fields and some helper methods to the enumeration class, with the following code:

 public enumcolorenum {RED ("red", "reds"), Green ("green", "cyan"), Blue ("blue", "blues"); //prevents field values from being modified, and the added fields also unify final to indicate constants    Private FinalString key; Private FinalString value; Privatecolorenum (String key,string Value) { this. Key =key;  this. Value =value; }    //get enumeration by Key     public Staticcolorenum Getenumbykey (String key) {if(NULL==Key) {            return NULL; }         for(colorenum temp:ColorEnum.values ()) {if(temp.getkey (). equals (key)) {returntemp; }        }        return NULL; }     publicString GetKey () {returnkey; }     publicString getValue () {returnvalue; }}

The usual, anti-compilation look at the changes? (in fact, We can see how static blocks and construction methods have changed.)

 public Final classColorenumextendsenum{ public Staticcolorenum[] values () {return(colorenum[]) $VALUES. Clone (); }     public Staticcolorenum valueOf (String s) {return(colorenum) enum.valueof (colorenum, s); }    //the Construction method adds our two new parameters to the original base .    PrivateColorenum (String s,inti, string s1, string S2) {        Super(s, i); Key=s1; Value=s2; }    //custom method to get the corresponding enumeration object with the key value     public Staticcolorenum Getenumbykey (String s) {if(NULL==S)return NULL; Colorenum acolorenum[]=Values (); inti =acolorenum.length;  for(intj = 0; J < i; J + +) {colorenum Colorenum=acolorenum[j]; if(colorenum.getkey (). equals (S))returncolorenum; }        return NULL; }     publicString GetKey () {returnkey; }     publicString getValue () {returnvalue; }     public Static FinalColorenum RED;  public Static FinalColorenum GREEN;  public Static FinalColorenum BLUE; //our custom two fields    Private FinalString key; Private FinalString value; Private Static FinalColorenum $VALUES []; Static{RED=NewColorenum ("red", 0, "red", "\u7efe\u3223\u58ca"); GREEN=NewColorenum ("green", 1, "green", "\u7f01\u80ef\u58ca")); BLUE=NewColorenum ("blue", 2, "blue", "\u9483\u6fca\u58ca"); $VALUES= (Newcolorenum[] {RED, GREEN, BLUE}); }}

3. Benefits of enumerations and differences from constant classes

1) enumerations can deal directly with the database, I usually use the varchar type store, corresponding to the enumerated constant Name. (there seems to be an enumeration type in the database, but it doesn't work.)

2) The switch statement supports enumeration type, when switch uses int, string type, because the value of instability tends to have a cross-border phenomenon, for this processing is often only through if condition filtering and the default module to Handle. In the case of enumerations, the type is qualified during compilation, and no bounds are allowed

3) when you use a constant class, you often have to determine whether the two are equal by equals, using enumerations because the constant value address is unique, you can use = = Direct comparison, performance will be improved

4) when a constant class is compiled, the value of the constant is compiled directly into the binary code of the class, and the value of the constant changes in the upgrade, and the class that references the constant needs to be recompiled because the old value is stored in it. The enumeration class compiles without compiling the constant value into the code, even if the value of the constant changes, it does not affect the class that references the Constant.

5) the enumeration class is compiled by default to final class, and inheritance is not allowed to prevent the quilt class from being Modified. Constant classes can be inherited, add fields, and so on, and easily lead to incompatible parent Classes.

  

.................. Welcome to Add!

Summary: the definition of constants is essential in development, although it is possible to define constants by constant classes or enumeration definitions to meet the requirements defined by Constants. however, It is best to use enumeration types for personal Advice.

4. Enumerating Common methods

  1.values () gets an array that stores all the constant instances in the Enumeration. Often mates with foreach to complete traversal

     for (colorenum temp:ColorEnum.values ()) {            System.out.println (temp);    }

  Operation Result:

RED GREEN BLUE

2. Construction method, Enumeration Construction method can only be decorated with the private modifier, reason does not need to explain ...

3.valueOf () Gets the corresponding enumeration instance by the constant Name.

Colorenum red = colorenum.valueof ("red");
System.out.println (red);

Java basics-enumeration

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.