Enum for Java Black-out operation

Source: Internet
Author: User
Tags comparable

Enum, which is an enumeration type, has a similar type in each programming language.

Because of the use of less, every time I see an enum will be daunting, because its grammar is really "do not press the regular card" Ah!

  

The general enum syntax is this:

 Public class MyClass {       privateenum Fruit {APPLE, ORANGE, GRAPE, BANANA}  // type definition     Private Fruit Fruit = fruit.apple;    // type use    Private void Useenum () {        if (fruit = = fruit.orange) {              System.out.println ("This is an orange") ;       }       }}

In the "Type definition" section above, it is found that the statement defining an enum type is quite different from the regular Java syntax, in which a class is generally defined as a variable, function, inner class, but this sentence feels nothing.

For enums, including similar enumeration types in C + +, I used to memorize them in a way that was different from other grammars. However, there is no egg, because the enumeration type is "unusual", and the use of less, will soon forget the specific syntax format.

Looking at "effective Java" the previous two days, it was found that there was a chapter devoted to enum, and the emphasis in the book was on the benefits of using enums, as well as the power of enum types in Java compared to other languages. I was smattering, but I began to pay attention to the special thing about enum.

Through various aspects of research, I found that the enum unknown insider, as well as a variety of black-out operations.

First, give the most important point: theenum is actually a class!

  With this logic, one half of the underlying syntax for an enum is understood. What if you change the word "enum" above to "class"? For example, the enumeration value on both sides with curly braces is the case, is not clear a lot?

  

Since enum is a class, I'll take the fruit class (can you call it that?) ) is defined in a different form

 Public classMyClass {Private classFruit {//change the enum to a new definition        PrivateFruit () {}//not allowed to be outside new fruit         Public Static FinalFruit APPLE =NewFruit ();  Public Static FinalFruit ORANGE =NewFruit ();  Public Static FinalFruit GRAPE =NewFruit ();  Public Static FinalFruit BANANA =NewFruit (); }        PrivateFruit Fruit = fruit.apple;//type Use    Private voidUseenum () {if(Fruit = =fruit.orange) {System.out.println ("This is an orange."); }       }}

  After reading this section of the conversion of the regular class code written, is not to exclaim: This special is not the same effect of the code!

Yes, this is the compiler's black-and-black operation, and the compiler will naturally try to convert it to this if it sees the keyword enum. Each enumeration value is not a 0-based int value in C + +, but rather a class instance. And because the final keyword was added, you know why the enumeration value is all capitalized? And because of adding the static keyword, why do you write "fruit.apple" static call form?

This is not the end, the above is just the principle of enum definition, enum in the specific use, how to traverse? How do i output the int value represented by each enumeration value? How do I output the literal string value of each enumeration value?

In fact, the fruit class given above is very incomplete, and the class that replaces the enum inherits from Java.lang.Enum, an abstract class that is automatically converted to the corresponding action in the Enum parent class when the compiler encounters an enum.

  

// definition of enum class  Public Abstract class extends Implements Serializable, comparable<e> {...}

For example, the fruit class above is actually like this.

Private class extends java.lang.Enum {      ...}

Consider the main members of the enum.

// This is the only two member variables of the Enum class, such as {apple,orange,grape},3 enumerated values are actually instances of subclasses of the Enum class, name is "APPLE", "ORANGE", "GRAPE", ordinal are 0 respectively, theprivatefinal String name;    // The literal string representation of the enumeration value, such as "APPLE", "ORANGE" , Private Final int ordinal;      // The int value represented by the enumeration value, similar to the enumeration type in C + +, can be understood as an index, in the order defined, the first is 0, the second is 1, and so on

These two property values can be obtained by similar to the Get method

    // get literal value     Public Final String name () {        return  name;    }         // Get index value     Public Final int ordinal () {        return  ordinal;    }

In addition, when outputting an enumeration value, the literal string value of the enumeration value is output because the ToString () method is called

    @Override    public  String toString () {        return  name;    }

The Enum class implements the comparable interface, which makes it possible to compare the enumeration values, in fact, the index value comparison

    // returns the difference between the index values of two enumeration values     Public Final int compareTo (E o) {        return ordinal-((enum<?>) o). Ordinal;    }

Enum also has two operations that should be implemented by the compiler invoking other methods of the Enum class.

The first is the values () method of the enum, which returns an array of all class instances, such as enum Fruit {Apple,orange,grape}, and returns the new Fruit[]{fruit.apple, Fruit.orange, Fruit.grape}, which can be used for traversal operations.

 for (Fruit f:fruit.values ()) {    ...}

The second is to use switch to make a choice, just write the enumeration value after the case, do not have to write the class name

Fruit f = fruit.apple; Switch (f) { case (APPLE) {  /// here does not have to be an instance (fruit.apple), the compiler automatically determines that this is an example of the Fruit class.    ...      Break ;}  Case (ORANGE) {   ...     Break ;} default  {   ...}}

about how this is done, is the compiler's own black-out operation, and here is not very clear.

In addition, the more advanced point is that the enum is completely considered a class, so you can rewrite your own method and add your own member variables. For example, implement arithmetic with an enumeration value:

         Public enumOperation {//Each enumeration value, the operation instance, actually defines an anonymous class at the time of Declaration, inherits the Operation class, and overrides the application method of the parent class operation in the anonymous subclass .PLUS {DoubleApplyDoubleXDoubleY) {returnx+y;}}, minus {DoubleApplyDoubleXDoubleY) {returnX-y;}, Times {DoubleApplyDoubleXDoubleY) {returnx*y;}}, DIVIDE {DoubleApplyDoubleXDoubleY) {returnx/y;}}; Abstract DoubleApplyDoubleXDoubley);//abstract methods defined in the Operation class}

The above code translates in fact is

     Public classOperationextendsenum{ Public Static FinalOperation PLUS =NewOperation () {//Anonymous Inner class@OverrideDoubleApplyDoubleXDoubleY) {returnx+y;}          }; ......          Abstract DoubleApplyDoubleXDoubley);//abstract methods defined in the Operation class}

Of course, you can implement the enum yourself, add member variables, overload constructors

 Public enumOperation {PLUS ("+"),//equals: public static final Operation PLUS = new operation ("+");Minus ("-"), Times ("*"), DIVIDE ("/"); Private FinalString symbol;//self-Added member variableoperation (String symbol) { This. symbol = symbol;}//constructor, the column enumeration value can be given in parentheses to give parameters, note that access rights should not be written as public@Override PublicString toString () {returnSymbol;}//overriding the ToString () method of the Enum class}

Finally, there is a small detail to note that the enumeration values are separated by ",". When there is only an enumeration value in the enum definition, there is nothing else, and the enumeration value can end without a ";". But there are other definitions, such as a member method, which must first write out the enumeration value, add another definition, and the enumeration value is finally added ";"

    Private enum Haha {                privatevoid  f () {            System.out.println ("!!!!!!!!!" );        };        face,sugar,apple;   // enumeration values must be first written    }    

One of the great uses of enumeration values is to replace scattered constant definitions (public static final XXX xx = xx), and these constants are only used for identifiers, and are not concerned with the constant value. After using the enum definition, you can perform type checking, which can be categorized when there are many constants, and you can output the literal value of an identifier.

Enum for Java Black-out operation

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.