Enumeration is a new data type in JDK 1.5. With enumeration, we can well describe some specific business scenarios, such as spring, summer, autumn and winter in a year, Monday to Sunday in a week, and various colors, as well as some state information, such as error codes.
Enumeration type not only exists in Java language, but also can be found in other languages, such as C ා and Python Wait, but I found that there are few people who use enumeration in actual projects, so this article will talk about the relevant contents of enumeration, so that friends can have a general impression of enumeration, so that when programming, at least they can think of a type like "enumeration".
The structure of this paper is as follows:
Seven ways to use enumeration
One of the important reasons why many people don't use enumeration is that they are not familiar with enumeration, so let's start with seven ways to use enumeration.
Usage 1: constant
Before JDK 1.5, we defined all constants as public static final... But with enumeration, we can define these constants as an enumeration class. The implementation code is as follows:
public enum ColorEnum { RED, GREEN, BLANK, YELLOW }
Usage 2: switch
Enumeration is used in switch judgment to make the code more readable. The implementation code is as follows:
enum ColorEnum { GREEN, YELLOW, RED } public class ColorTest { ColorEnum color = ColorEnum.RED; public void change() { switch (color) { case RED: color = ColorEnum.GREEN; break; case YELLOW: color = ColorEnum.RED; break; case GREEN: color = ColorEnum.YELLOW; break; } } }
Usage 3: add method in enumeration
We can add some methods to enumeration to make enumeration have more features. The implementation code is as follows:
public class EnumTest { public static void main(String[] args) { ErrorCodeEnum errorCode = ErrorCodeEnum.SUCCESS; System.out.println("Status code:" + errorCode.code() + " Status information:" + errorCode.msg()); } } enum ErrorCodeEnum { SUCCESS(1000, "success"), PARAM_ERROR(1001, "parameter error"), SYS_ERROR(1003, "system error"), NAMESPACE_NOT_FOUND(2001, "namespace not found"), NODE_NOT_EXIST(3002, "node not exist"), NODE_ALREADY_EXIST(3003, "node already exist"), UNKNOWN_ERROR(9999, "unknown error"); private int code; private String msg; ErrorCodeEnum(int code, String msg) { this.code = code; this.msg = msg; } public int code() { return code; } public String msg() { return msg; } public static ErrorCodeEnum getErrorCode(int code) { for (ErrorCodeEnum it : ErrorCodeEnum.values()) { if (it.code() == code) { return it; } } return UNKNOWN_ERROR; } }
The execution results of the above procedures are as follows:
Status code: 1000 status information: success
Usage 4: override enumeration method
We can override some methods in enumeration to realize our own business. For example, we can override toString() method. The implementation code is as follows:
public class EnumTest { public static void main(String[] args) { ColorEnum colorEnum = ColorEnum.RED; System.out.println(colorEnum.toString()); } } enum ColorEnum { RED("gules", 1), GREEN("green", 2), BLANK("white", 3), YELLOW("yellow", 4); // Member variable private String name; private int index; // Construction method private ColorEnum(String name, int index) { this.name = name; this.index = index; } //Coverage method @Override public String toString() { return this.index + ": " + this.name; } }
The execution results of the above procedures are as follows:
1: Red
Usage 5: implement the interface
Enumeration classes can be used to implement interfaces, but cannot be used to inherit classes, because enumeration inherits by default java.lang.Enum Class. In the Java language, multiple interfaces are allowed, but multiple parent classes cannot be inherited. The implementation code is as follows:
public class EnumTest { public static void main(String[] args) { ColorEnum colorEnum = ColorEnum.RED; colorEnum.print(); System.out.println("Color:" + colorEnum.getInfo()); } } interface Behaviour { void print(); String getInfo(); } enum ColorEnum implements Behaviour { RED("gules", 1), GREEN("green", 2), BLANK("white", 3), YELLOW("yellow", 4); private String name; private int index; private ColorEnum(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; } }
The execution results of the above procedures are as follows:
1: Red
Color: Red
Usage 6: organize enumeration classes in the interface
We can create multiple enumeration classes in an interface, and use it to well realize "polymorphism", that is, we can gather enumeration classes with the same characteristics but different implementation in one interface, and the implementation code is as follows:
public class EnumTest { public static void main(String[] args) { // Assign the first enumeration class ColorInterface colorEnum = ColorInterface.ColorEnum.RED; System.out.println(colorEnum); // Assign a second enumeration class colorEnum = ColorInterface.NewColorEnum.NEW_RED; System.out.println(colorEnum); } } interface ColorInterface { enum ColorEnum implements ColorInterface { GREEN, YELLOW, RED } enum NewColorEnum implements ColorInterface { NEW_GREEN, NEW_YELLOW, NEW_RED } }
The execution results of the above procedures are as follows:
RED
NEW_RED
Usage 7: use enumeration set
There are also two enumeration collection classes related to enumeration classes in Java language java.util.EnumSet And java.util.EnumMap , you can use them to achieve more functions.
Using EnumSet can ensure that the elements are not repeated and can get the elements within the specified range. The example code is as follows:
import java.util.ArrayList; import java.util.EnumSet; import java.util.List; public class EnumTest { public static void main(String[] args) { List<ColorEnum> list = new ArrayList<ColorEnum>(); list.add(ColorEnum.RED); list.add(ColorEnum.RED); // Repeating element list.add(ColorEnum.YELLOW); list.add(ColorEnum.GREEN); // Remove duplicate data EnumSet<ColorEnum> enumSet = EnumSet.copyOf(list); System.out.println("duplicate removal:" + enumSet); // Get enumeration of the specified range (get all failed states) EnumSet<ErrorCodeEnum> errorCodeEnums = EnumSet.range(ErrorCodeEnum.ERROR, ErrorCodeEnum.UNKNOWN_ERROR); System.out.println("All failed states:" + errorCodeEnums); } } enum ColorEnum { RED("gules", 1), GREEN("green", 2), BLANK("white", 3), YELLOW("yellow", 4); private String name; private int index; private ColorEnum(String name, int index) { this.name = name; this.index = index; } } enum ErrorCodeEnum { SUCCESS(1000, "success"), ERROR(2001, "parameter error"), SYS_ERROR(2002, "system error"), NAMESPACE_NOT_FOUND(2003, "namespace not found"), NODE_NOT_EXIST(3002, "node not exist"), NODE_ALREADY_EXIST(3003, "node already exist"), UNKNOWN_ERROR(9999, "unknown error"); private int code; private String msg; ErrorCodeEnum(int code, String msg) { this.code = code; this.msg = msg; } public int code() { return code; } public String msg() { return msg; } }
The execution results of the above procedures are as follows:
De duplication: [RED, GREEN, YELLOW]
All failure status: [ERROR, SYS_ERROR, NAMESPACE_NOT_FOUND, NODE_NOT_EXIST, NODE_ALREADY_EXIST, UNKNOWN_ERROR]
EnumMap is similar to HashMap, but it is a Map collection specially designed for enumeration. Compared with HashMap, its performance is higher, because it abandons the structure of linked list and red black tree internally and uses array as the structure of data storage.
The basic use examples of EnumMap are as follows:
import java.util.EnumMap; public class EnumTest { public static void main(String[] args) { EnumMap<ColorEnum, String> enumMap = new EnumMap<>(ColorEnum.class); enumMap.put(ColorEnum.RED, "gules"); enumMap.put(ColorEnum.GREEN, "green"); enumMap.put(ColorEnum.BLANK, "white"); enumMap.put(ColorEnum.YELLOW, "yellow"); System.out.println(ColorEnum.RED + ":" + enumMap.get(ColorEnum.RED)); } } enum ColorEnum { RED, GREEN, BLANK, YELLOW; }
The execution results of the above procedures are as follows:
RED: RED
Precautions for use
The relevant provisions of enumeration in Alibaba Java development manual are as follows. We need to pay attention to them when using them.
[mandatory] all enumeration type fields must have comments indicating the purpose of each data item.
[reference] enumeration class names are suffixed with Enum. Enumeration member names need to be all uppercase, and words are separated by underscores. Note: enumeration is actually a special constant class, and the constructor is forced to be private by default. Positive example: enumeration name is ProcessStatusEnum member name: SUCCESS / UNKNOWN_REASON.
If enumeration is not used
Before enumeration was born, that is, before JDK version 1.5, we usually used the int constant to represent enumeration. The implementation code is as follows:
public static final int COLOR_RED = 1; public static final int COLOR_BLUE = 2; public static final int COLOR_GREEN = 3;
But there are two problems with int types:
First, int type itself does not have security. If a programmer defines int with less final keywords, there will be the risk of being modified by others. On the contrary, enumeration class is a constant class, and there is no risk of being modified (see the second half for the reasons);
Second, the semantics of int type is not clear enough. For example, if we print only numbers like 1... 2... 3 in the console, we certainly don't know what it means.
Then someone said, use constant characters. It doesn't mean you don't know the semantics, does it? The implementation example code is as follows:
public static final String COLOR_RED = "RED"; public static final String COLOR_BLUE = "BLUE"; public static final String COLOR_GREEN = "GREEN";
However, there is also a problem in this way. Some junior programmers will not play according to routines. They may directly use string values for comparison rather than enumeration fields. The implementation example code is as follows:
public class EnumTest { public static final String COLOR_RED = "RED"; public static final String COLOR_BLUE = "BLUE"; public static final String COLOR_GREEN = "GREEN"; public static void main(String[] args) { String color = "BLUE"; if ("BLUE".equals(color)) { System.out.println("blue"); } } }
So when we change the value in the enumeration, the program will be cool.
Enumerate usage scenarios
The common use scenario of enumeration is a single example. Its complete implementation code is as follows:
public class Singleton { // Enumeration types are thread safe and will only be loaded once private enum SingletonEnum { INSTANCE; // Declare singleton object private final Singleton instance; // instantiation SingletonEnum() { instance = new Singleton(); } private Singleton getInstance() { return instance; } } // Get instance (singleton object) public static Singleton getInstance() { return SingletonEnum.INSTANCE.getInstance(); } private Singleton() { } // Class method public void sayHi() { System.out.println("Hi,Java."); } } class SingletonTest { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); singleton.sayHi(); } }
Because enumeration can only be loaded once when the class is loaded, it is thread safe, which is also the main reason why the author of Effective Java strongly recommends using enumeration to implement a single example.
Knowledge expansion
Why is enumeration thread safe?
This starts with the bytecode generated by enumeration. First, we define a simple enumeration class:
public enum ColorEnumTest { RED, GREEN, BLANK, YELLOW; }
Then we compile the above code into bytecode, as follows:
public final class ColorEnumTest extends java.lang.Enum<ColorEnumTest> { public static final ColorEnumTest RED; public static final ColorEnumTest GREEN; public static final ColorEnumTest BLANK; public static final ColorEnumTest YELLOW; public static ColorEnumTest[] values(); public static ColorEnumTest valueOf(java.lang.String); static {}; }
From the above results, it can be seen that the enumeration class will be compiled into a common class decorated by final, and all its properties will be decorated by static and final keywords, so the enumeration class will be loaded and initialized by the JVM when the project starts, and the execution process is thread safe, so the enumeration class is also thread safe.
Tip: the process of code decompilation is to use javac command to compile bytecode (. class), and then use javap command to view compiled bytecode.
Enumeration comparison tips
It is enough for us to use = = in enumeration comparison, because enumeration classes are created when the program is loaded (it is not new), and enumeration classes are not allowed to directly use the new keyword outside to create enumeration instances, so we have only one object in essence when using enumeration classes, so it is enough to use = = in enumeration comparison.
In addition, when we look at the equlas() source code of enumeration, we can see that the = = method is called directly inside it. The source code is as follows:
public final boolean equals(Object other) { return this==other; }
summary
In this paper, we introduce seven ways to use enumeration class: constant, switch, adding method in enumeration, overriding enumeration method, implementing interface, organizing enumeration class in interface and using enumeration collection, etc. then we talk about how to use int type and String if not using enumeration class There are some disadvantages of types: the semantics is not clear enough, easy to be modified, and there is the risk of misuse, so we should try to use enumeration classes in the appropriate environment. And we also talked about the use scenarios of enumeration classes -- single examples, and why enumeration classes are safe. Finally, we talked about the tips of enumeration comparison. I hope this article can help you.
View & thank you
https://www.iteye.com/blog/so...
The Chinese official account of the Java community is returned to dry cargo and 50 original dry cargo Top lists are received.
The Chinese official account of the Java community is returned to dry cargo and 50 original dry cargo Top lists are received.