Summary of seven common uses of Java enumeration (must see)

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.

Java code

Usage 2: switch

JDK1. The switch statements before 6 only support int, char and enum types. Using enumeration can make our code more readable.

Java code

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.

Java code

Usage 4: override enumeration method

Here is an example of toString () method coverage.

Java code

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.

Java code

Usage 6: use interface to organize enumeration

Java code

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.

The above is a summary of the seven common uses of Java enumeration (must see) brought by Xiaobian. I hope you can support programming tips~

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>