Java enum type enum

Source: Internet
Author: User

syntax for enumerations
1.Enum is all called enumeration, the Chinese commonly known as enumeration class, has learned C + + and other languages of people, should be to it knows.
In the Java language Specification, however, it was introduced in the JDK version 5 and stored in the Java.lang package. In the Java version of the enum is essentially a syntactic sugar, which is declared in the following way:

"Code 1"

Package com.enumtest;public enum color{    red,blue,black,yellow,green   //Note there can be no semicolon}   
  An enum is a keyword used to declare an enumeration, and the class that declares the definition implicitly inherits a parent class (java.lang.enum<e>), so the enumeration cannot be inherited, but the interface can still be implemented.
The parent class has two private property name (the name of the enumeration type) and ordinal (the ordinal of the enumeration instance was created), exposed by name () and ordinal () respectively.
Each enumeration instance defined in the enumeration type is mapped to the subclass of the enum, and the name of its instance and the order defined in the enumeration type are passed into the constructor: protected Enum (String name, int ordinal).
2. If you want to understand the enum more clearly, you can use the Anti-compilation tool to decompile your own definition of the enumeration to a glance, it is a normal class, but the Java language Specification from the code point of view is limited, the execution of the JAVAP com.enumtest.Color command is as follows:
"Code 2"
Package com.enumtest;  Public final class Color extends  java.lang.enum{public     static final Color RED;     public static final Color BLUE;     public static final Color BLACK;     public static final Color YELLOW;     public static final Color GREEN;     static {};     public static color[] values ();     
3. All enum classes inherit the methods of the enum, which we will describe in detail below.
(1) ordinal () method: Returns the order of enumeration values in the enumeration class. This order depends on the order in which the enumeration values are declared.
Color.RED.ordinal (); Results returned: 0
Color.BLUE.ordinal (); Results returned: 1
(2) CompareTo () method: Enum implements the Java.lang.Comparable interface, so you can compare the order of objects like the specified object. The CompareTo in the enum returns the difference in order of the two enumeration values. Of course, the premise is that two enumeration values must belong to the same enumeration class, otherwise a classcastexception () exception will be thrown. (Visible source code)
Color.RED.compareTo (Color.Blue); return result-1
(3) The values () method: A static method that returns an array that contains all the enumeration values.
Color[] Colors=color.values ();
for (Color c:colors) {
System.out.print (c+ ",");
}//return Result: Red,blue,black Yellow,green,
(4) ToString () method: Returns the name of the enumeration constant.
Color c=color.red;
System.out.println (c);//return Result: RED
(5) ValueOf () Method: This method is relative to the ToString method and returns an enumeration constant of the specified enumeration type with the specified name.
Color.valueof ("BLUE"); return Result: Color.Blue
(6) Equals () method: Compares references to two enum class objects.
4. If the defined enumeration has its own constructor, it must declare private.

5. Note the following differences:
"Code 3"

Enum Color3{}enum color4{    red}enum color5{    RED;} Enum color6{    RED;    public void Test () {}}enum color7{public    Void Test () {}   //RED;  Error!!!! }enum color8{    ;    public void Test () {}}
In enum Color3 is an empty enumeration, there is a red enumeration value in Enum Color4 and Color5, followed by a semicolon or no semicolon, or, if you add a method after the enumeration value, add a semicolon at the end of the enumeration value, such as an enum COLOR6 If, like enum COLOR7, you want to define an enumeration value that is illegal after the method, the compiler prompts for an error, and of course it can be defined as an enum COLOR8, notice the semicolon before the method test ().

Usage of enumerations
(1) commonly used to classify the same class of constants. See Code 1.
(2) When declaring an interface method, the input parameter type takes an enumeration more rigorously than the original type value constant.
(3) Constants are sometimes more than just a value, and may contain multiple attributes, which is a good time to enumerate
(4) A constant object needs to read its descriptive information or UI display information from the configuration file, which is also suitable for enumeration
(5) From the Java syntax level, enumerations can be used in switch and can be compared directly in the IF.
"Code 4"

Package Com.enumtest;public enum Color {red,blue,black,yellow,green;//Note there is a semicolon public static void Valueprint (Color                color) {switch (color) {case RED:System.out.println (RED);            Break                Case BLUE:System.out.println (BLUE);            Break                Case BLACK:System.out.println (BLACK);            Break                Case YELLOW:System.out.println (YELLOW);            Break                Case GREEN:System.out.println (GREEN);            Break        Default:break;        }} public static void Main (String args[]) {color color = color.red;        Valueprint (color);    Enumtest.valueprint (color);                }}class enumtest{public static void Valueprint (color color) {switch (color) {case RED:  System.out.println (color.red);//Note that color.red here cannot be written in red, and the case must be written in red.              Break                Case BLUE:System.out.println (Color.Blue);            Break                Case BLACK:System.out.println (Color.Black);            Break                Case YELLOW:System.out.println (Color.yellow);            Break                Case GREEN:System.out.println (Color.green);            Break        Default:break; }    }}
Operation Result:
Redred
(6) It is best to use the public final decoration when declaring enumeration properties, which is very convenient.
(7) When customizing enumerations, it is recommended not to use the own name () and ordinal () method return values to convert from the original value type, so that the business does not rely on its enumerated name and order
"Code 5"
Package com.enumtest;public enum color2{    Red ("Red", 1), Blue ("Blue", 2), Black ("Black", 3), YELLOW ("Yellow", 4), Green ("Green", 5);    Public final String name;    public final int index;    Private Color2 (String name, int index)    {        this.name = name;        This.index = index;    }    public static String getName (int index)    {for        (Color2 c:color2.values ())        {            if (c.getindex () = = Index )            {                return c.name;            }        }        return null;    }    public static void Main (string[] args)    {        System.out.println (GetName (1));    }    Public String getName ()    {        return name;    }    public int GetIndex ()    {        return index;    }}
Running Result: Red
(8) Overloaded enumeration method ToString
"Code 6"

Package com.enumtest;public enum color2{    Red ("Red", 1), Blue ("Blue", 2), Black ("Black", 3), YELLOW ("Yellow", 4), Green ("Green", 5);    Public final String name;    public final int index;    Private Color2 (String name, int index)    {        this.name = name;        This.index = index;    }    public static String getName (int index)    {for        (Color2 c:color2.values ())        {            if (c.getindex () = = Index )            {                return c.tostring ();            }        }        return null;    }    public static void Main (string[] args)    {        System.out.println (GetName (1));    }    @Override public    String toString ()    {        return this.index+ "_" +this.name;    }    Public String getName ()    {        return name;    }    public int GetIndex ()    {        return index;    }}
(9) Implement the interface. All enumerations are inherited from the Java.lang.Enum class. Because Java does not support multiple inheritance, enumeration objects can no longer inherit from other classes.
"Code 7"
Package Com.enumtest;public interface behaviour{    void print ();    String getInfo ();}
"Code 8"
Package Com.enumtest;public enum COLOR9 implements behaviour{red    ("Red", 1), Blue ("Blue", 2), Black ("Black", 3), YELLOW ("Yellow ", 4), Green (" Green ", 5);    Public final String name;    public final int index;    Private Color9 (String name, int index)    {        this.name = name;        This.index = index;    }    @Override public    void print ()    {        System.out.println (this.index+ ":" +this.name);    }    @Override public    String getInfo ()    {        return this.name;    }}
(10) You can create an enum class that is considered an ordinary class. Except that it cannot inherit other classes. (Java is a single inheritance, it has inherited an enum), you can add other methods, overriding its own methods.
The values () method is the static method that the compiler inserts into the enum definition, so when you convert an enum instance up to a parent enum, values () is inaccessible. Workaround: There is a getenumconstants () method in class, so even if the enum interface does not have the values () method, we can still get all the enum instances through the class object.
"Code 9"
Package Com.enumtest;public enum Color {    red,blue,black,yellow,green;//Note there is a semicolon public    void print ()    { For        (Color c:color.class.getenumconstants ())        {            System.out.println (c.tostring ());        }    }    public static void Main (String args[])    {        Color.RED.print ();}    }
(12) A subclass cannot be inherited from an enum, and if an element in an enum needs to be extended, an enumeration that implements that interface is created inside an interface to group the elements. The enumeration elements are grouped to be reached.
"Code 10"
Package Com.enumtest;public interface food{    enum Coffee implements food     {        black_coffee, Decaf_coffee, LATTE;    }    Enum dessert implements food    {        fruit,cake,gelato;    }}
Java.util.EnumSet and Java.util.EnumMap are two enumeration collections. Enumset guarantees that the elements in the set are not duplicated; The key in Enummap is the enum type, and value can be any type.
"Code 11"
Package Com.enumtest;import Java.util.enummap;import Java.util.enumset;import java.util.set;public class LightTest{        public enum light{RED (1), GREEN (2), YELLOW (3);        public final int NCode;        Private light (int nCode) {this.ncode = NCode;        }} public static void Testtraversalenum () {light[] alllight = Light.values ();        for (light alight:alllight) {System.out.println (Alight.name () + "" +alight.ordinal () + "" +alight); }} public static void Testenummap () {enummap<light,string> currenummap = new Enummap<light,stri        Ng> (Light.class);        Currenummap.put (light.red, "Red");        Currenummap.put (Light.green, "green");        Currenummap.put (Light.yellow, "yellow");        set<light> set = Currenummap.keyset ();        for (light alight:set) {System.out.println (Alight.name () + "" +alight.ordinal () + "" +alight); }} public static void Testenumset () {       enumset<light> Currenumset = Enumset.allof (Light.class);        for (light alightsetelement:currenumset) {System.out.println (alightsetelement);        }} public static void Main (string[] args) {testtraversalenum ();        Testenummap ();    Testenumset (); }}
Run Result: (slightly)
(14) Use the Enum's responsibility chain (Chain of Responsibility). This is related to the design pattern of the responsibility chain mode. Solve a problem in a number of different ways. Then link them together. When a request arrives, it traverses the chain until a solution in the chain can handle the request.

Java enum type enum

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.