How to use Java enumeration

How to use Java enumeration

Foreword the flag and status in your code should be replaced by enumeration

Many people say that enumeration is rarely used or even not used in actual development. Because their code is often like this:

Then, they use this class as follows:

Well, then they say, "I rarely use enumeration in actual development."

Of course, they mean that enum enum is rarely used.

However, what I want to say is that all the above codes should be implemented with enum.

Why?

Because their code is completely based on trust in teammates, suppose a wonderful teammate did this:

You say, what happens to the heroes on the screen?

In short, if you often use such code in actual programming, it's time to learn enum.

Enum: why use enum types

There are enumerations everywhere in life, including "natural enumerations", such as planets, days of the week, and enumerations designed by us, such as CSDN tab labels, menus, etc.

There are generally two ways to express enumeration in Java code. One is int enumeration, but enum enumeration. Of course, we all know that enum enumeration is the real enumeration provided by Java.

So why do we use enum enumeration types? Let's take a look at how we represented enumeration before Java 1.5 when there was no enumeration type.

Take the eight planets as an example. Each planet corresponds to an int value, which we will probably write like this

This is called int enumeration mode. Of course, you can also use string enumeration mode. No matter what method is adopted, this method is very poor in type safety and convenience. If the variable planet represents a planet, the user can assign a value that is not included in our enumeration value, such as planet = 9. Only God knows which planet it is; Moreover, it is difficult for us to calculate how many planets there are, and it is also difficult for us to traverse the planets, and so on.

Now we use enumeration to create our planet.

The above is the simplest enumeration. Let's call it planet 1.0. In this version of planet enumeration, we realize a function that any variable of planet type can be guaranteed by the compiler. Any non null object passed to the parameter must belong to one of the eight planets.

Then, we upgrade planet. Java allows us to add arbitrary methods to enumeration types. Here is the code in the introduction. Let's experience the knowledge points of enumeration constructor, public method, enumeration traversal and so on.

Run weighttable and the print results are as follows:

In this applet, we use the values () method of enumeration. This method returns the collection of enumeration variables in the enumeration type, which is very practical.

Enumerating advanced calculator operator classes

In the example in the previous section, we used the public methods of enumeration classes. In this section, we take the calculator operator operation enumeration class as an example to see how to implement the

Each enumerated object performs different operations.

First, we can easily think of a method. In the public method, use switch to judge the enumeration type, and then perform different operations. The code is as follows:

This code does realize our requirements, but it has two disadvantages.

First, we have to throw an exception at the end or add default to the switch, otherwise we can't compile, but obviously, the branch of the program won't enter the exception or default.

Secondly, this code is very fragile. If we add a new operation type, but forget to add the corresponding processing logic in the switch, there will be a problem when we execute a new operation.

Fortunately, Java enumeration provides a function called constant specific method implementation.

We only need to declare an abstract method in the enumeration type, and then override this method in each enumeration constant. The implementation is as follows:

In this way, we will never forget to add the corresponding processing logic after adding a new operator, because the compiler will prompt us that we must override the apply method.

However, one disadvantage of this constant specific implementation is that it is difficult for you to share code between enumerated constants.

Let's take the enumeration of week x as an example. Monday to Friday are working days. One logic is executed, and another logic is executed on Saturday, Sunday and rest days.

If you still use constant specific methods, the code written may be like this:

Obviously, there are quite a lot of duplicate code in our code.

So how to optimize it? Let's think like this. Monday, Tuesday and so on are enumerations. Aren't working days and rest days also enumerations? Can we pass in a daytype enumeration of working days and rest days to the constructor of day? This is a method called policy enumeration given in the book. The code is as follows:

By means of policy enumeration, we delegate the day processing logic to daytype. Readers can understand the mystery in detail.

Enumerate the use of enumset

Enumset provides a very convenient way to create an enumeration set. Here is the code to experience it

In this example, we use enumset Of method to easily create an enumeration collection.

Enumerating the use of map enummap

Suppose that herb has an enumeration attribute type (annual, perennial, biennial)

Herb:

Now, suppose we have a herb array. We need to classify and store the herb array according to type.

So next, we need to create a map. Value must be the collection of herb. So what is the key?

Some people will use the ordinal () method of the enumeration type. This function returns the int type, indicating the position of the enumeration traversal in the enumeration class. This has obvious disadvantages. Because your key type is int, you can't guarantee that the incoming int will correspond to the variables in the enumeration class.

Therefore, in the selection of key, there is no doubt that you can only use the enumeration type, that is, herb Type。

Finally, there is another question. What map do you want to use? Java provides a special map for enumeration types, called enummap. Compared with other maps, this map is faster in processing enumeration types. Interested students can study the internal implementation of this map.

Let's see how to use enummap:

summary

Compared with int enumeration, enum enumeration has obvious advantages in type safety and convenience. Enum provides rich functions for enumeration, such as constant specific method implementation and policy enumeration mentioned in the article. Enumset and enummap are two collections designed for enumeration. When enum sets are used in actual development, please give priority to these two collections.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

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
分享
二维码
< <上一篇
下一篇>>