1. Background
Before the Java language has been introduced, the common pattern for indicating an enum type is to declare a set of int constants. The code we used to define before using the public final static method is as follows, using 1 to represent spring, 2 to represent summer, 3 to represent autumn, and 4 to represent winter.
public class Season { public static final int SPRING = 1; public static final int SUMMER = 2; public static final int AUTUMN = 3; public static final int WINTER = 4;}This method is called the int enumeration pattern. But what's wrong with this model? We have used it for so long, so there should be no problem. Usually the code we write takes into account its security, ease of use and readability. First, let’s consider its type safety. Of course this pattern is not type-safe. For example, we design a function that requires a certain value in spring, summer, autumn and winter. However, with the int type, we cannot guarantee that the value passed in is legal. The code looks like this:
private String getChineseSeason(int season){ StringBuffer result = new StringBuffer(); switch(season){ case Season.SPRING : result.append("Spring"); break; case Season.SUMMER : result.append("Summer"); break; case Season.AUTUMN : result.append("Autumn"); break; case Season.WINTER : result.append("Winter"); break; default : result.append("Season None on Earth"); break; } return result.toString(); } public void doSomething(){ System.out.println(this.getChineseSeason(Season.SPRING));//This is a normal scenario System.out.println(this.getChineseSeason(5));//This is an abnormal scenario, which leads to type insecurity issues}The program getChineseSeason(Season.SPRING) is the method we expect to use. But getChineseSeason(5) is obviously not the case, and the compilation is very passive. We don’t know what happens at runtime. This obviously does not conform to the type safety of Java programs.
Next, let's consider the readability of this pattern. Most occasions when using enumerations, I need to be convenient to get string expressions of enum type. If we print out the int enumeration constants, what we see is a set of numbers, which is not very useful. We may think of using String constants instead of int constants. Although it provides printable strings for these constants, it causes performance problems, because it relies on string comparison operations, so this pattern is also something we do not expect. Considering both type safety and program readability, the disadvantages of the int and String enumeration patterns are revealed. Fortunately, since the Java 1.5 release, another alternative solution has been proposed that avoids the disadvantages of the int and String enumeration patterns and provides many additional benefits. That is the enum type. The following chapters will introduce the definitions, features, application scenarios, and advantages and disadvantages of enumeration types.
2. Definition <br /> Enum type refers to a legal type composed of a fixed set of constants. In Java, the keyword enum is used to define an enum type. The following is the definition of the java enum type.
public enum Season { SPRING, SUMMER, AUTUMN, WINER;} 3. Features
Java's statements that define enum types are very simple. It has the following characteristics:
1) Use the keyword enum 2) Type name, such as Season 3) A string of allowed values, such as the spring, summer, autumn, winter, and seasons defined above 4) Enumerations can be defined separately in a file or embedded in other Java classes.
In addition to such basic requirements, users have some other options
5) Enumerations can implement one or more interfaces (Interfaces) 6) New variables can be defined 7) New method can be defined 8) Classes that vary according to specific enumeration values can be defined
4. Application scenarios
Taking the type safety mentioned in the background as an example, rewrite that code with an enum type. The code is as follows:
public enum Season { SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4); private int code; private Season(int code){ this.code = code; } public int getCode(){ return code; }}public class UseSeason { /** * Convert English season to Chinese season* @param season * @return */ public String getChineseSeason(Season season){ StringBuffer result = new StringBuffer(); switch(season){ case SPRING : result.append("[Chinese: spring, enumeration constant:" + season.name() + ", data:" + season.getCode() + "]"); break; case AUTUMN : result.append("[Chinese: autumn, enumeration constant:" + season.name() + ", data:" + season.getCode() + "]"); break; case SUMMER : result.append("[Chinese: summer, enumeration constant:" + season.name() + ", data:" + season.getCode() + "]"); break; case WINTER : result.append("[Chinese: winter, enumeration constants:" + season.name() + ", data:" + season.getCode() + "]"); break; default : result.append("Season without Earth" + season.name()); break; } return result.toString(); } public void doSomething(){ for(Season s: Season.values()){ System.out.println(getChineseSeason(s));//This is a normal scenario} //System.out.println(getChineseSeason(5)); //The compiler is already failing here, which ensures type safety} public static void main(String[] arg){ UseSeason useSeason = new UseSeason(); useSeason.doSomething(); }}[Chinese: Spring, Enumeration Constant: SPRING, Data: 1] [Chinese: Summer, Enumeration Constant: SUMMER, Data: 2] [Chinese: Autumn, Enumeration Constant: AUTUMN, Data: 3] [Chinese: Winter, Enumeration Constant: WINTER, Data: 4]
Here is a question, why do I want to add the domain to the enum type? The purpose is to associate the data with its constants. For example, 1 represents spring and 2 represents summer.
5. Summary
So when should you use enums? Whenever a fixed set of constants is needed, such as the days of a week, the seasons of the year, etc. Or a collection of all the values it contains before we compile. The Java 1.5 enumeration can meet the requirements of most programmers, and its concise and easy-to-use characteristics are very prominent.
6. Usage
Usage 1: Constant
public enum Color { RED, GREEN, BLANK, YELLOW }Usage 2: switch
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 the enum
public enum Color { RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4); // Member variable private String name; private int index; // Construct method private Color(String name, int index) { this.name = name; this.index = index; } // Normal 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: Methods to overwrite enumeration
public enum Color { RED("red", 1), GREEN("green", 2), BLANK("white", 3), YELLO("yellow", 4); // Member variable private String name; private int index; // Construct method private Color(String name, int index) { this.name = name; this.index = index; } // Overwrite method @Override public String toString() { return this.index+"_"+this.name; } }Usage 5: Implement the interface
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; // Construct method private Color(String name, int index) { this.name = name; this.index = index; } // Interface method @Override public String getInfo() { return this.name; } //Interface method @Override public void print() { System.out.println(this.index+":"+this.name); } }Usage 6: Use interface to organize enumeration
public interface Food { enum Coffee implements Food{ BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO } enum Dessert implements Food{ FRUIT, CAKE, GELATO } }The above is all about this article, I hope it will be helpful to everyone's learning.