Java enumeration (enum) explains seven common uses
JDK1. 5 introduces a new type enumeration. Although it is a "small" function in Java, it brings "big" convenience to my development.
Usage 1: constant
At jdk1 Before 5, we defined constants as public static fianl. Now, with enumeration, you can group related constants into an enumeration type, and enumeration provides more methods than constants.
Usage 2: switch
JDK1. The switch statements before 6 only support int, char and enum types. Using enumeration can make our code more readable.
Usage 3: add a new method to the enumeration
If you want to customize your own methods, you must add a semicolon at the end of the Enum instance sequence. Moreover, Java requires that enum instances must be defined first.
Usage 4: override enumeration method
Here is an example of toString () method coverage.
Usage 5: implement interface
All enumerations are inherited from Java Lang. enum class. Because Java does not support multi inheritance, enumerated objects can no longer inherit other classes.
Usage 6: use interface to organize enumeration
Usage 7: about the use of enumeration collection
java. util. Enumset and Java util. Enummap is a collection of two enumerations. Enumset ensures that the elements in the set are not repeated; The key in enummap is of enum type, while the value can be of any type. The use of these two sets will not be described here. You can refer to the JDK documentation.
For the implementation details and principle of enumeration, please refer to:
Reference: Thinking in Java, 4th Edition http://www.jb51.net/books/75540.html
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.