Java Enum Enumeration

Source: Internet
Author: User

Saw something, found that the Java enumeration is not very understanding, and then look for a check to remember.

Why use enumerations? The enumeration was not jdk1.5 until after 1.5, and Java was not supported for enumeration. Why use enumerations?

If a variable has only a few possible values, we can use an int, string, or other type of variable to represent it, although we can do this, but we can't guarantee

The value of the use time must be we contract several values, this will inevitably create unnecessary trouble, and the enumeration can avoid such errors, enumeration type is actually the value of the variables enumerated,

The value of a variable is limited to the range of values enumerated, and once an enumeration type variable is defined, the variable can only define values within the range, so we don't have to think too much when we use it.

Again in Java Declaration enum with the enum keyword, in fact our definition of enumerations are integrated from the Java.lang.Enum class, because Java is but inherited all of our defined enumerations can no longer go

Inherit another class.

  

 Public enum color{    Red,white,bule}

The above is a simple enumeration that declares its own enumeration type, color, which has only three types Red,white,bule

It's easy to use when you use it again.

class testenum{    publicstaticvoid  main (string[] args)    {        =  color.red;        SYSTEM.OUT.PRINTLN (color);        System.out.println ("-----------------");          for (Color color2:Color.values ())        {            System.err.println (color2);     }}}

Enumeration has a very convenient way of values, this method can be found in Java.lang.annotation.ElementType , the method provides us with a very convenient way to enumerate.

That's what the JDK says.

Returns an array containing the constants of this enum type, in the order they is declared. This method is used to

Iterate over the constants as follows:

For (ElementType c:elementtype.values ())        System.out.println (c);

Of course this is not an enum of the values of the method, but they are the same, I did not find where to declare this values, and then found on the Internet such a statement:

The values () method, which you should understand as the unique method of the type enum, where the enum is declaring a type, is different from the enum, as we know that int declares a type, and the integer is his outer class, and for int, there is a method +,-, multiplication, But in the integer we do not +,-multiplication form of the method, here is the same reason
Enum as a new type, you should interpret him as int,double,string the same type, "I think that's the answer."

Enum also has a oridinal method that returns the order of enumeration values in the enumeration class, depending on the order in which the enumeration values are declared.

The CompareTo () method of the enum, which compares this enumeration with the order of the specified objects. Returns a negative integer, 0, or a positive integer, respectively, when the object is less than, equal to, or greater than the specified object. Enumeration constants can only be compared with other enumeration constants of the same enumeration type. The natural order in which this method is implemented is the order in which the constants are declared

* When defining an enumeration type, it is essentially redefining a category, but many details are done by the compiler,
* So, to some extent, the enum keyword acts like a class interface
* When you use Enum to define an enumeration type, the type that is essentially defined is inherited from the Java.lang.Enum type.
* While the members of each enumeration are actually an instance of the defined enumeration type, they are all preset to final, so they cannot be changed
* They are also static members, so they can be used directly from the type name, and most importantly, they are public.
* In other words, when an enumeration type is defined, it is time to compile to determine how many instances of the enumeration type,
* We were unable to create new instances with this enumeration type during the early run, and these instances were fully identified during compilation.

Enumeration can also have a constructor method, there are member variables, there are methods in general enumeration is almost the same as the normal Java class, the following points:

The constructor for an enumeration class can only use the private access modifier, and if its constructor's access control is omitted, the private adornment is used by default. This guarantees that external code cannot newly construct an instance of the enumeration class.

All instances of an enumeration class must be explicitly listed in the enumeration class, or the enumeration class will never produce an instance. When these instances are listed, the public static final decoration is automatically added without the programmer being explicitly added.

  Note that the variable and method definitions must be placed after all the enumeration value definitions, or the compiler will give an error.

  

 Packagecom.tai.enums; Public enumcoin{Penny ("Hello"), Nickel ("World"), Dime ("Welcome"), Quarter ("Hello World");//Public static final Coin Pennys ("111");        PrivateString value;  PublicString GetValue () {returnvalue; } Coin (String value) { This. Value =value; }         Public Static voidMain (string[] args) {Coin Coin=quarter;    System.err.println (Quarter.getvalue ()); }}

There is also a comprehensive application of the enumeration used in traffic light control as explained by Master Zhang Xiaoxiang.

 Public enumLamp {/*Each enumeration element represents a control light in one Direction*/s2n ("N2s", "s2w",false), s2w ("n2e", "e2w",false), e2w ("w2e", "E2s",false), E2s ("w2n", "s2n",false),     /*The following elements represent the lights in the opposite direction of the elements above, and their "opposite direction lights" and "next lights" should be disregarded! */N2s (NULL,NULL,false), N2E (NULL,NULL,false), W2E (NULL,NULL,false), w2n (NULL,NULL,false),     /*The lights from the south to the east and the right turn from the west to the north are not controlled by traffic lights, so they can be assumed to always be green .*/s2e (NULL,NULL,true), E2N (NULL,NULL,true), n2w (NULL,NULL,true), W2s (NULL,NULL,true); PrivateLamp (String opposite,string Next,Booleanlighted) {          This. opposite =opposite;  This. Next =Next;  This. Lighted =lighted; }      /*whether the current light is green*/         Private Booleanlighted; /*The corresponding direction of green at the same time as the current lamp*/         PrivateString opposite; /*When the light turns red now a green light*/         PrivateString Next;  Public Booleanislighted () {returnlighted; }     /*** When a light turns green, the light that corresponds to the direction will turn green .*/          Public voidLight () { This. Lighted =true; if(Opposite! =NULL) {lamp.valueof (opposite). Light (); } System.out.println (name ()+ "lamp is green, there should be a total of 6 directions below to see the car through!" "); }     /*** When a lamp turns red, the light in the corresponding direction will turn red, and the light in the next direction will turn green *@returnthe next light to turn green*/          PublicLamp BlackOut () { This. Lighted =false; if(Opposite! =NULL) {lamp.valueof (opposite). BlackOut (); } Lamp Nextlamp=NULL; if(Next! =NULL) {Nextlamp=lamp.valueof (next); System.out.println ("Green light from" + name () + "--------> Switch to" +next);         Nextlamp.light (); }         returnNextlamp; } }

Java Enum Enumeration

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.