Java Enumeration type enum
Enumeration syntax
1. Enum is called enumeration, which is commonly known as enumeration class in Chinese. People who have studied C/C ++ or other languages should have a slight knowledge of it.
But it is introduced in the Java language specification in JDK 5 and stored in the java. lang package. In Java, the Enum is actually a syntactic sugar. The declaration method is as follows:
[Code 1]
Package com. enumtest; public enum Color {RED, BLUE, BLACK, YELLOW, GREEN // note that there is no semicolon}
Enum is a keyword used to declare enumeration. All declared classes implicitly inherit a parent class (java. lang. Enum ). Therefore, enumeration cannot be inherited, but interfaces can still be implemented.
The parent class has two private attributes: name (name of Enumeration type) and ordinal (ordinal number of instance creation), which are exposed through name () and ordinal.
Every enumeration instance defined in the enumeration type will be mapped to the Enum subclass. The instance name and the sequence defined in the enumeration type will be passed into this constructor: protected Enum (String name, int ordinal ).
2. if you want to know more about Enum, you can use the decompilation tool to decompile the enumeration defined by yourself. It is a common class, but the Java language specification is limited from the Code perspective, execute javap com. enumtest. the 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(); public static Color valueOf(java.lang.String); }
3. All enumeration classes inherit the Enum method. The following describes these methods in detail.
(1) ordinal () method: return the order of the enumerated values in the enumerated classes. This order depends on the order in which enumeration values are declared.
Color. RED. ordinal (); // The returned result is 0.
Color. BLUE. ordinal (); // The returned result is 1.
(2) compareTo () method: Enum implements the java. lang. Comparable interface, so it can be compared to the order of the specified object. CompareTo in Enum returns the order difference between the two enumerated values. Of course, the premise is that the two enumerated values must belong to the same enumeration class, otherwise the ClassCastException () exception will be thrown. (Specific visible source code)
Color. RED. compareTo (Color. BLUE); // return result-1
(3) values () method: static method. An array containing all enumerated values is returned.
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 enumerated constant.
Color c = Color. RED;
System. out. println (c); // The returned result is RED.
(5) valueOf () method: This method corresponds to the toString method, and an enumerated constant of the specified enumeration type with the specified name is returned.
Color. valueOf ("BLUE"); // return result: Color. BLUE
(6) equals () method: Compares the references of two enumeration class objects.
4. If the defined enumeration has its own constructor, it must be declared 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, it is an empty enumeration. in enum Color4 and Color5, there is a RED enumeration value, which can be followed by a plus sign or no plus sign. if you add a method after the enumerated value, add a semicolon at the end of the enumerated value, such as enum Color6. If you want to define the enumerated value after the method like enum Color7, the compiler will prompt an error; of course, you can also define it like enum Color8. Pay attention to the semicolon before the test () method.
Enumeration usage
(1) It is often used to classify constants of the same class. See Code 1.
(2) When declaring an interface method, the input parameter type enumeration is more rigorous than the original type value constant.
(3) constants are often not only a single value, but may contain multiple attributes. In this case, enumeration is suitable.
(4) Sometimes a constant object needs to read its description information or UI display information from the configuration file, which is also suitable for enumeration.
(5) In terms of Java syntax, enumeration can be used in switch, and can be directly compared in if.
Code 4]
Package com. enumtest; public enum Color {RED, BLUE, BLACK, YELLOW, GREEN; // note that the 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); // pay attention to the Color here. RED cannot be written as RED, while RED must be written as RED in case. 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 ;}}}
Running result:
REDRED
(6) It is best to use public final to declare enumeration attributes, which is very convenient to use.
(7) When customizing enumeration, we do not recommend that you use the built-in name () and ordinal () Methods to convert the returned values to the original value type, so that the business does not rely on the enumerated names 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) method toString for reload Enumeration
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) Implementation interface. All enumerations are inherited from the java. lang. Enum class. Because java does not support multi-inheritance, enumeration objects cannot inherit 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 and regard it as a common class. Except that it cannot inherit other classes. (Java is a single inheritance, it has inherited Enum), you can add other methods to overwrite its own method.
(11) The values () method is the static method inserted by the compiler into the enum definition. Therefore, when you transform the enum instance to the parent class Enum, the value () is inaccessible. Solution: There is a getEnumConstants () method in the Class, so even if the Enum interface does not have the values () method, we can still get all enum instances through the Class object.
Code 9]
Package com. enumtest; public enum Color {RED, BLUE, BLACK, YELLOW, GREEN; // note that the 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) The subclass cannot be inherited from enum. If you need to extend the elements in enum, create an enumeration to implement this interface within an interface to group the elements. To group the enumerated elements.
Code 10]
package com.enumtest;public interface Food{ enum Coffee implements Food { BLACK_COFFEE, DECAF_COFFEE,LATTE; } enum Dessert implements Food { FRUIT,CAKE,GELATO; }}
(13) java. util. EnumSet and java. util. EnumMap are two enumeration sets. EnumSet ensures that the elements in the set are not repeated. The key in EnumMap is of the enum type, and the value can be of 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
CurrEnumMap = new EnumMap
(Light. class); currEnumMap. put (Light. RED, "RED"); currEnumMap. put (Light. GREEN, "GREEN"); currEnumMap. put (Light. YELLOW, "YELLOW"); Set
Set = currEnumMap. keySet (); for (Light aLight: set) {System. out. println (aLight. name () + "" + aLight. ordinal () + "" + aLight) ;}} public static void testEnumSet () {EnumSet
CurrEnumSet = EnumSet. allOf (Light. class); for (Light aLightSetElement: currEnumSet) {System. out. println (aLightSetElement) ;}} public static void main (String [] args) {testTraversalEnum (); testEnumMap (); testEnumSet ();}}
Running result: (omitted)
(14) use the Chain of Responsibility (Responsibility) of enum, which is related to the Responsibility Chain mode of the design model. Solve a problem in multiple ways. Then link them together. When a request arrives, traverse the chain until a solution in the chain can process the request.