Recently I discovered that there are a lot of ways to use int enumeration in the company's code, and I also saw some ways to use enum for enumeration. I was very curious about this, conducted research, and then wrote this article to summarize why we should use enum.
#Why should Java use enumerations?
Suppose there are now two order types: reservation orders and non-reservation orders.
Requirement 1: The method submitOrder performs different processing according to different order types.
Requirement 2: Set the order type to an object: OrderResult.
The following are implemented using two enumeration methods.
int enumeration
class IntEnumExample{ private static final PRE_ORDER = 1; private static final NOT_PRE_ORDER = 2; public void submitOrder(int orderType, OrderResult orderResult){ orderResult.setType(orderType); if(orderType == PRE_ORDER){ do something to process preOrder }else if(orderType == NOT_PRE_ORDER){ do something to process other order } } public static void main(String [] args){ IntEnumExample example = new IntEnumExample(); //passing wrong type to the method, however, no compile error and runtime exception here, the bug is hard to be discerned. example.submitOrder(3, orderResult); } }
As you can see from the above example, there are several disadvantages to using int enumeration:
1. The int enumeration does not perform type checking. You can pass in any int value to the submitOrder method above
2. The readability of the code is low. If there is no documentation or source code, you do not know the meaning of the value passed to submitOrder.
Not only that, just like the problem I found when I modified the sonar scanning code in the project before, many people did not define the int value as static final when using the int enumeration as in the above example. If you forget to define a variable as final, the value of the int enumeration can be modified. If you forget to define a variable as static, it may happen that the int value has not been initialized when using it.
In short, it will cause bugs.
Let’s see how to do the same thing using enum.
class IntEnumExample{ private enum ORDER_TYPE { NOT_PRE_ORDER(1),PRE_ORDER(2); private final int value; private ORDER_TYPE(int value){ this.value = value; } } public void submitOrder(ORDER_TYPE orderType, OrderResult orderResult){ orderResult.setType(orderType); if(orderType == ORDER_TYPE.PRE_ORDER){ do something to process preOrder }else if(orderType == ORDER_TYPE.NOT_PRE_ORDER){ do something to process other order } } public static void main(String [] args){ IntEnumExample example = new IntEnumExample(); //compiler will complain error here, if argument is not the type in the enum. example.submitOrder(ORDER_TYPE.PRE_ORDER, orderResult); } }
As you can see from the above code, enum elegantly solves the problem in the previous example.
1. The compiler will perform type checking on enum. If the type does not match, the compiler will directly report an error.
2. Compared with the method of directly passing int values from int enumeration types, the way enum passes enum type objects makes the code more readable and the passed enumeration type is clear at a glance.
3. The object in the enum type itself is static final.
Important tip:
It is also worth mentioning that if you sometimes want to assign an int value to each enumeration type, you should use enum in the above example defined way.
private enum ORDER_TYPE { NOT_PRE_ORDER(1),PRE_ORDER(2); private final int value; private ORDER_TYPE(int value){ this.value = value; } }
The nature of enum is also a class, so the method ORDER_TYPE(int value) is the constructor of this enumeration type. Therefore, each enumeration type needs to pass the corresponding value to the constructor during initialization, such as: PRE_ORDER(2).
In this case, if you want to get the int value corresponding to the enumeration type, you can get it through ORDER_TYPE.PRE_ORDER.value.
The usage of enum is mentioned separately because some people may directly use the ordinal() method in enum to directly realize the association between the enum type and the int type. The ordinal() method returns the ordinal number of the enum type when it was defined. For example, ORDER_TYPE.PRE_ORDER.value.ordinal() returns a value of 0. Therefore, it seems that obtaining the int value corresponding to the enumeration type can also be achieved through ORDER_TYPE.PRE_ORDER.value.ordinal() 1.
Don’t use the ordinal() method! Don't use the ordinal() method! Don't use the ordinal() method! Say important things three times, why?
Ordinal numbers are very unreliable and can be changed. Suppose one day the definition of ORDER_TYPE changes and several types need to be added, or the order in which NOT_PRE_ORDER and PRE_ORDER are accidentally changed, such as:
private enum ORDER_TYPE { PRE_ORDER,NOT_PRE_ORDER; }
This will cause serious bugs, which are difficult to find. There will be no errors during compilation or runtime.
So, don’t rely on the ordianl() method.
Related learning recommendations: java basic tutorial
The above is the detailed content of Why does java use enumerations?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment