In the past, there was only one vague concept for Enum, which was used in recent projects, so I made a special research:
Java's Enum Enumeration type has finally appeared in j2se1.5. I thought it was just a chicken rib, but it was dispensable. After all, have you ever had a good life without it for so many years? Today, I read thinking in Java 4th edition, which contains a saying: "Sometimes it is precisely because of it that you can" elegantly and cleanly "solve the problem. Elegance and clarity are important. They formally differentiate successful and failed solutions. The solution to failure is because others have no legal principle. "Can I use the enum Enumeration type to make the previous clumsy code elegant and simple? However, I am also thinking about another question. Will the use of new technologies bring more burden to technicians?
"One danger of learning the new version of the language is the crazy use of the new syntax structure"
As a New Keyword introduced by Sun, Enum looks like a special class. It can also have its own variables, define its own methods, and implement one or more interfaces. When declaring an Enum type, we should note that the enum type has the following features.
1. It cannot have a public constructor. This ensures that the customer Code cannot create an Enum instance.
2. All enumerated values are public, static, and final. Note that this is only for enumeration values. We can define other types of non-enumeration variables like variables defined in common classes. These variables can use any modifier you want.
3. Enum implements the java. Lang. Comparable interface by default.
4. Enum overwrites the tostring method. Therefore, if we call color. Blue. tostring (), the "blue" string is returned by default ".
5. Enum provides a valueof method, which corresponds to the tostring method. Calling valueof ("blue") will return color. Blue. Therefore, we need to note this when rewriting the tostring method. For example, we should override the valueof method.
6. Enum also provides the values method, which allows you to easily traverse all enumeration values.
7. enum also has an oridinal method. This method returns the order of the enumerated values in the enumerated classes. This order depends on the order in which the enumerated values are declared. Here, color. red. ordinal () returns 0.
After learning about these basic features, let's take a look at how to use them.
1. traverse all enumerated values. Once we know the values method, we can easily use the foreach loop to traverse the enumerated values.
for(Color c: Color.values()) System.out.println(“find value:” + c);
2. Define methods and variables in Enum. For example, we can add a method for color and return a random color.
Public Enum color {red, green, blue;/** defines a variable to indicate the number of enumerated values. * (I'm a bit surprised why Sun didn't directly provide the size method for Enum ). */Private Static int number = color. values (). length;/*** returns an enumerated value @ return a random Enum value. */public static color getrandomcolor () {long random = system. currenttimemillis () % number; Switch (INT) random) {Case 0: Return color. red; Case 1: Return color. green; Case 2: Return color. blue; default: Return color. red ;}}}
It can be seen that there is no difference between defining variables in enumeration types and defining methods and variables in common classes. The only thing to note is that the variables and method definitions must be placed behind the definitions of all enumeration values. Otherwise, the compiler will give an error.
3. we already know that Enum provides tostring, valueof, and other methods. In many cases, we need to override the default tostring method. How can we do this for Enum. In fact, this is no different from the tostring Method for overwriting a common class.
public String toString(){ switch (this){ case Red: return "Color.Red"; case Green: return "Color.Green"; case Blue: return "Color.Blue"; default: return "Unknow Color"; } }
At this time, we can see that the previous traversal code is used to print out
Color. Red
Color. Green
Color. Blue
Instead
Red
Green
Blue.
We can see that tostring is indeed overwritten. Generally, when overwriting tostring, we should also overwrite the valueof method to maintain their consistency.
4. Although Enum cannot have a public constructor, we can still define a private constructor and use it within enum. Or use the color example.
public enum Color { Red("This is Red"), Green("This is Green"), Blue("This is Blue"); private String desc; Color(String desc){ this.desc = desc; } public String getDesc(){ return this.desc; } }
Here we provide a description for each color, and then define a constructor to accept this description. Note that the constructor cannot be public or protected, so that the constructor can only be used internally, and the customer Code cannot create an instance with a new enumerated value. This is also reasonable because we know that the enumerated value is a constant of public static final.
5. to implement a specific interface, we already know that Enum can define variables and Methods. To implement an interface, it is the same as implementing an interface in a common class. This is not an example here.
6. define the methods of enumeration values. We can see that we can define some methods for enum. In fact, we can even define methods for each enumerated value. In this way, the previous example of overwriting tostring can be rewritten as this.
public enum Color { Red { public String toString(){ return "Color.Red"; } }, Green { public String toString(){ return "Color.Green"; } }, Blue{ public String toString(){ return "Color.Blue"; } }; }
Logically, this is clearer than the tostring method that originally provided a "global. In general, Enum, as a newly defined type, is intended to help programmers write code more easily and easily. I personally feel that it generally does not require too many advanced features of enum, otherwise, it is contrary to the easy-to-understand intention.
First, let's take a look at the simple application of enum. The following simple code already contains most of the functions provided by enum.
1. Application of Enum, including definition, traversal, switch, enumset, enummap, etc.
Package COM. autonavi. test; import Java. util. enummap; import Java. util. enumset;/*** Java Enumeration type Enum Usage Details * myenum can store multiple enumeration types * enumeration types can also be directly declared as classes, * Public Enum state {On, off} can be used as a Java file * @ author heqingfei */public class myenum {// to define an Enum Enumeration type at the same level as the class and interface, including instance on, offpublic Enum state {On, off} public Enum country {China, Japan} // test method public static void main (string [] ARGs) {// direct variable enumfor (State S: state. values () {system. out. println (S. name ();} // The direct variable enumfor (Country C: Country. values () {system. out. println (C. name ();} // The combination of switch and enum uses state switchstate = state. off; Switch (switchstate) {case off: system. out. println ("off"); break; Case on: system. out. println ("On"); break;} system. out. println ("******* enumset usage *********"); // use enumset stateset = enumset. allof (state. class); For (State S: stateset) {system. out. println (s);} system. out. println ("******* enummap usage *********"); // use enummap statemap = new enummap (state. class); statemap. put (state. on, "is on"); statemap. put (state. off, "Is Off"); For (State S: state. values () {system. out. println (S. name () + ":" + statemap. get (s);} system. out. println ("=========================="); // The enumeration can be called State state1 = myenum. state. off; system. out. println (state1.name (); system. out. println ("======================"); State [] state2 = myenum. state. values (); For (State state: state2) {system. out. println (state. name ());}}}
The following content may be boring, but it is definitely worth a glimpse.
1.
Public class State {
Public static final int on = 1;
Public static final int off = 0;
}
What's wrong? It's been a long time for everyone to do this. It's okay.
First, it is not type-safe. You must make sure it is an int
Second, make sure that the range is 0 and 1.
Finally, most of the time you print out, you only see 1 and 0,
But the person who does not see the Code does not know your attempt.
So, discard all your old public static final constants.
2. You can create an Enum class and think of it as a common class. Except that it cannot inherit other classes. (Java is a single inheritance, and it has inherited Enum ),
You can add other methods to overwrite them.
3. You can use Enum for the switch () parameter.
4. 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.
5. The subclass cannot be inherited from enum. If you need to extend the elements in Enum, you can create an enumeration for this interface within an interface to group the elements. To group the enumerated elements.
6. Use enumset to replace the flag. Enum requires that its members be unique, but Enum cannot delete the add element.
7. The key of enummap is Enum, and value is any other object.
8. Enum allows programmers to write methods for eunm instances. Therefore, you can assign different behaviors to each Enum instance.
9. Use the responsibility chain (chain of responsibility) of enum. This is the responsibility chain mode related to 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.
10. State Machine with Enum
11. Use Enum for multi-channel distribution
Usage 1: Constant
Before jdk1.5, we define constants as public static fianl ..... Now, with enumeration, You can group related constants into one Enumeration type, and enumeration provides more methods than constants.
public enum Color { RED, GREEN, BLANK, YELLOW}
Usage 2: Switch
The switch statement before jdk1.6 only supports int, Char, and enum types, and uses enumeration to make our code more readable.
enum Signal {GREEN, YELLOW, RED}public class TrafficLight {Signal color = Signal.RED;public void change() {switch (color) {case RED:color = Signal.GREEN;break;case YELLOW:color = Signal.RED;break;case GREEN:color = Signal.YELLOW;break;}}}
Usage 3: Add a new method to Enumeration
If you want to customize your own method, you must add a semicolon at the end of the enum instance sequence. And
Java requires that the enum instance be defined first.
Public Enum color {red ("red", 1), Green ("green", 2), blank ("white", 3), yello ("yellow", 4 ); // member variable private string name; private int index; // constructor private color (string name, int index) {This. name = Name; this. index = index;} // common method public static string getname (INT index) {for (color C: color. values () {If (C. getindex () = index) {return C. name ;}} return NULL;} // Get Set Method Public String getname () {return name;} public void setname (string name) {This. name = Name;} public int getindex () {Return Index;} public void setindex (INT index) {This. index = index ;}}
Usage 4: override Enumeration Method
The following is an example of overwriting the tostring () method.
Public Enum color {red ("red", 1), Green ("green", 2), blank ("white", 3), yello ("yellow", 4 ); // member variable private string name; private int index; // constructor private color (string name, int index) {This. name = Name; this. index = index;} // override method @ overridepublic string tostring () {return this. index + "_" + this. name ;}}
Usage 5: Implementation Interface
All enumerations are inherited from the java. Lang. Enum class. Because Java
Multi-inheritance is not supported, so enumeration objects cannot inherit other classes.
Public Interface Behaviour {void print (); string getinfo ();} public Enum color implements behaviour {red ("red", 1), Green ("green", 2 ), blank ("white", 3), yello ("yellow", 4); // member variable private string name; private int index; // constructor private color (string name, int index) {This. name = Name; this. index = index;} // interface method @ overridepublic string getinfo () {return this. name;} // interface method @ overridepublic void print () {system. out. println (this. index + ":" + this. name );}}Usage 6: organize enumeration Using Interfaces
public interface Food {enum Coffee implements Food{BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO}enum Dessert implements Food{FRUIT, CAKE, GELATO}}
Usage 7: Use of enumeration Sets
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. The usage of these two sets is not described here. You can refer to the JDK documentation.
Then write a tool class to encode and decode enumeration types:
Private Static string [] showcollecttype = {"service collection", "performance Collection "};
/*** Encode the collection type * @ Param collecttype * @ return */public static collecttype encodecollecttype (string collecttype) {collecttype colltype = collecttype. collservice; If (collecttype. equals ("service collection") {colltype = collecttype. collservice;} else if (collecttype. equals ("performance Collection") {colltype = collecttype. collperform;} return colltype ;}
/*** Decodes the collection type * @ Param colltype * @ return */public static string decodecollecttype (collecttype colltype) {string collecttype = "service collection"; if (colltype. equals (collecttype. collservice) {collecttype = "service collection";} else if (colltype. equals (collecttype. collperform) {collecttype = "performance Collection";} return collecttype ;}
/*** Get collection type */public static string [] getshowcollecttype () {return showcollecttype ;}