Using enum expressions to take values

Source: Internet
Author: User
Tags comparable

Question, why do constants need to be defined with an enum instead of final to define a member variable or define a constant in interface?

First to understand what an enum class is: The Enum class is a class in the Java.lang package, which is the common base class for all enumerated types in the Java language.

First, the definition:
Public abstract class Enum<e extends enum<e>> implements Comparable<e>, Serializable
    1. Abstract class
First, abstract classes cannot be instantiated, so we cannot use the NEW keyword to declare an enum in a Java program, if you want to define a syntax that you can use:
enum enumname{     value1,    value2;    Method1 () {};    Method2 () {}; }

Second, when you see an abstract class, the first impression is definitely inheritable, but I'm sorry, the Enum class cannot be inherited, why can't an abstract class be inherited? What is the enum class that the enum defines? Is it not an inheritance of an enum? With these questions, we'll decompile the following code.

Enum Color {RED, BLUE, GREEN}

The compiler will compile them into the following code

Public final class Color extends enum<color> {public     static final color[] values () {           return (color[]) $VALU Es.clone ();     }     public static Color valueOf (String name) {...}     Private Color (String s, int i) {           super (S, i);     }     public static final Color RED;     public static final Color BLUE;     public static final Color GREEN;     private static final Color $VALUES [];//returns all values for the enumeration. The compiler inserts a method that is nowhere to be found in     static {           red = new Color ("Red", 0);           Blue = new Color ("Blue", 1);           Green = new Color ("Green", 2);           $VALUES = (new color[] {RED, BLUE, GREEN});}     

From the post-compilation code, we find that the compiler does not let us inherit the enum, but when we use the Enum keyword to define an enumeration, he will help us inherit the Java.lang.Enum class by default after compiling, rather than inheriting the object class by default, as with other classes. And with the enum declaration, the class is added to the final declaration by the compiler, so the class cannot be inherited. PS: Because JVM class initialization is thread-safe, you can implement a thread-safe singleton pattern with an enumeration class.

    1. Implement comparable and Serializable interfaces
Enum implements the Serializable interface, which can be serialized. Enum implements the comparable interface, can be compared, by default, only the same type of enum is compared (cause see later), to achieve a comparison between different types of enum, only the CompareTo method can be replicated.
    1. Generics <e extends Enum<e>>
First we "translate" the enum<e extends enum> what the meaning, and then to explain why Java to use it. Let's look at a more common generic type: List. This generic means that the list is stored in a string type, telling the compiler to accept the string type, and automatically helps us to type a string when the content is removed from the list. So enum<e extends enum> can temporarily understand that the contents of the enum are E extends enum types. Here's e we understand as enumerations, extends represents an upper bound, such as: list< The content in extends Object>,list can be an object or a class that extends from object. This is the meaning of extends. Therefore, the E extends enum is represented as an enumeration type that inherits the enum type. Then, Enum<e extends enum> is not difficult to understand, is an enum only accept an Enum or his subclass as a parameter. It is equivalent to passing a subclass or itself as an argument to itself, causing some special grammatical effects. Second, the attribute in the enum, there are two member variables, one is the name (name), and the other is the ordinal (ordinal). The ordinal is an enumeration constant that represents the position in the enumeration, starting at 0 and incrementing in turn.
Private final String name;     Public final String name () {           return name;     }     private final int ordinal;     Public final int ordinal () {           return ordinal;      }
Third, the method
    1. Construction method
As we said earlier, an enum is an abstract class that cannot be instantiated, but he also has a constructor, and from the code we have compiled in the previous example, we have found the constructor of the enum, which has only one constructor for the type of protection in the enum:
Protected Enum (String name, int ordinal) {           this.name = name;           This.ordinal = ordinal;     }

The article starts with the anti-compilation code in private Color (String s, int i) {super (S, i);} The super (S, i) in the call to the constructor of this protection type in enum to initialize name and ordinal.

    1. Other methods
Public String toString () {           return name;     }     Public final Boolean equals (Object other) {           return this = = other     ;}     Public final int hashcode () {           return Super.hashcode ();     }     Protected final Object Clone () throws Clonenotsupportedexception {           throw new clonenotsupportedexception ();     Public     Final int compareTo (E o) {           enum other = (enum) o;           Enum self = this;           if (self.getclass () = Other.getclass () &&//Optimization                     self.getdeclaringclass ()! = Other.getdeclaringclass ())                throw new ClassCastException ();           return self.ordinal-other.ordinal;     }     Public final class<e> Getdeclaringclass () {           Class clazz = GetClass ();           Class zuper = Clazz.getsuperclass ();           return (Zuper = = Enum.class)? Clazz:zuper;      }

Outreach: Values () from the above anti-compilation code we can also see a $values[]  of things, then what is this thing? Yes, he is. The values () method that we are using to define the enum class. Habitual we want Ctrl + Left key to enter the method, but I'm sorry, we can't have any idea about this method. So what exactly is this method, and why is it so mysterious? After reviewing the data, it is known that the compiler automatically inserts some methods when compiling the Enum class, which is the method.   Example 1:
Public enum Commandtoken implements BaseEnum {TECH (5, "/152", "/tech"), Zhineng (6, "/152/153", "/tech/zhi Neng "), Jiankang (7,"/154 ","/jiankang "), Yinshi (8,"/154/155 ","/jiankang/yinshi "), Money (9,"     /156 ","/money "), Yinhang (Ten,"/156/157 ","/money/yinhang "); private int value; Command value private String URL; The URL of the matching private String catagory;           The directory that is replaced by private commandtoken (int value, string URL, String catagory) {this.value = value;           This.url = URL;     This.catagory = catagory;     } public int GetValue () {return value;     } public String GetUrl () {return URL;     } public String Getcatagory () {return catagory; public static Commandtoken Parse (String value) {commandtoken[] vs = values ();//values () is actually commandtoken  . values ();           A compiler automatically generates a static method for (Commandtoken S:vs) {if (Value.equals (S.url)) {          return s;     }} return null;     } @Override Public String toString () {return catagory;     } @Override public int toint () {//TODO auto-generated method stub return 0;           }}public string getcolumnpath (string url) {string columnpathtem = null;           Commandtoken token = commandtoken.parse (URL);           if (token! = null) {Columnpathtem = Token.tostring ();           }else{columnpathtem = null;     } return Columnpathtem; }

Public interface BaseEnum {          /**      * Returns the string representation of the object      * @return String *      /Public     string toString ();     /**      * Returns the integer representation of the object      * @return integral type      *     /public int toint ();     }

  

Example 2: Now, suppose you want to implement a method that generates an enumeration value from an integer value for the enumeration, you can do this:
Public enum Typeenum implements BaseEnum {//Video (1, "videos")--video = new Typeenum (1, "video") Video (1, "video"), A          Udio (2, "audio"), Text (3, "text"), Image (4, "image");     member variable private int value;     private String name; Constructs a method, custom, adds a semicolon at the end of the enum instance sequence, and Java requires that an enum instance (for example, video) typeenum (int value, String name) be defined first {This.valu           e = value;     THIS.name = name;     }//provides access to the Get Set method public int GetValue () {return value;     } public String GetName () {return name;     } public void SetValue (int value) {this.value = value;     } public void SetName (String name) {this.name = name;                }//Normal method public static typeenum getbyvalue (int value) {for (Typeenum typeEnum:TypeEnum.values ()) {                if (Typeenum.value = = value) {return typeenum; }} throw new IllegalArgumentException ("No element matches" + Value);     }//Overwrite the ToString method of the object class public String tostring () {return this.value + "_" + this.name; }//Implements the interface method because Java does not support multiple inheritance, so only by implementing an interface @Override public int toint () {//TODO auto-generated Method St     UB return 0; }}
Getbyvalue (int) is the method for integer value to enumerate the values. Call the values () method to get all the values under the enumeration, and then iterate through each value below the enumeration and whether the given integer matches, and if the match returns directly, throws a IllegalArgumentException exception if no matching value, indicating that the argument is not valid, and that it has the effect of validation. in summary, we can see that the new enumeration introduced in JDK5 perfectly solves the problem caused by the constant to represent the discrete amount, greatly enhancing the readability, ease of use and maintainability of the program, and extending it on this basis so that it can be used like a class. It is also a step up for the representation of the discrete amount of java. Therefore, if in Java need to represent a limited number of colors, patterns, categories, states, and so on, the form is discrete, the expression is extremely clear, you should try to discard the practice of the constant representation, and the enumeration as the primary choice. after figuring out what an enum is, back to our question, why use enum to define constants without the normal static class final static
    1. Ensure type safety. For example, constants such as status, order status, alarm status, and so on, if passed to final static string type, in the number of received parameters, may be a value outside the state, this will produce an exception
    2. More standardized. have their own name,ordinal.
    3. Increased readability and maintainability of the program
Additional ways to use enumeration classes: http://blog.csdn.net/qq_27093465/article/details/52180865

Using enum expressions to take values

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.