In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Why Java enumeration is recommended". In daily operation, I believe many people have doubts about why Java enumeration is recommended. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "Why Java enumeration is recommended?" Next, please follow the editor to study!
Enumeration types not only exist in the Java language, but can also be found in other languages, such as C# and Python, etc., but I find that very few people use enumerations in actual projects, so this article will talk about enumerations, so that friends can have a general impression of enumerations, so that at least one type of enumeration can be thought of when programming.
The structure of this article is as follows:
Seven ways to use enumerations an important reason why many people don't use enumerations is that they are not familiar with enumerations, so let's start with the seven ways to use enumerations.
Usage 1: constant
Before JDK 1.5, we defined constants as public static final... But with enumerations, we can define these constants as an enumeration class, with the following implementation code:
Public enum ColorEnum {RED, GREEN, BLANK, YELLOW}
Usage 2: switch
Enumerations are 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 methods to enumerations
We can add some methods to the enumeration to make the enumeration have more features, and 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 results of the above procedures are as follows:
Status code: 1000 status information: success
Usage 4: override enumeration methods
We can override some of the methods in the enumeration to implement our business. For example, we can override the 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 ("red", 1), GREEN ("green", 2), BLANK ("white", 3), YELLOW ("yellow", 4); / / member variable private String name; private int index / / Constructor private ColorEnum (String name, int index) {this.name = name; this.index = index;} / / override method @ Override public String toString () {return this.index + ":" + this.name;}}
The 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 enumerations inherit java.lang.Enum classes by default, which allows multiple interfaces to be implemented in Java language, but cannot inherit multiple parent classes. 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 ("red", 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 results of the above procedures are as follows:
1: red
Color: red
Usage 6: organize enumerated classes in the interface
We can create multiple enumerated classes in an interface, which can be used to implement "polymorphism", that is, we can aggregate enumerated classes with the same characteristics but with slight implementation differences in one interface. 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 the 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 results of the above procedures are as follows:
RED
NEW_RED
Usage 7: use enumerated collections
Related to enumerated classes in the Java language, there are also two enumerated collection classes java.util.EnumSet and java.util.EnumMap, which can be used to achieve more functionality.
Use EnumSet to ensure that the elements do not repeat and get the elements within the specified range. The sample 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 list = new ArrayList (); list.add (ColorEnum.RED); list.add (ColorEnum.RED); / / repeating element list.add (ColorEnum.YELLOW); list.add (ColorEnum.GREEN) / / deduplicated EnumSet enumSet = EnumSet.copyOf (list); System.out.println ("deduplicated:" + enumSet); / / get enumerations in the specified range (get all failed states) EnumSet errorCodeEnums = EnumSet.range (ErrorCodeEnum.ERROR, ErrorCodeEnum.UNKNOWN_ERROR); System.out.println ("all failed states:" + errorCodeEnums) }} enum ColorEnum {RED ("red", 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 results of the above procedures are as follows:
Weight removal: [RED, GREEN, YELLOW]
All failure states: [ERROR, SYS_ERROR, NAMESPACE_NOT_FOUND, NODE_NOT_EXIST, NODE_ALREADY_EXIST, UNKNOWN_ERROR]
EnumMap is similar to HashMap, except that it is an Map collection specially designed for enumerations and has higher performance than HashMap because it internally abandons the structure of linked lists and red-black trees and uses arrays as the structure of data storage.
The basic usage examples of EnumMap are as follows:
Import java.util.EnumMap; public class EnumTest {public static void main (String [] args) {EnumMap enumMap = new EnumMap (ColorEnum.class); enumMap.put (ColorEnum.RED, "red"); 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 results of the above procedures are as follows:
RED: red
Matters needing attention
Ali "Java Development Manual" on the relevant provisions of enumerations are as follows, we need to pay a little attention to when using.
[mandatory] all enumerated type fields must be annotated indicating the purpose of each data item.
[reference] enumerated class names are suffixed with Enum, enumerated member names need to be capitalized, and words are separated by underscores. Description: enumerations are actually special constant classes, and constructors are forced to be private by default. Positive example: enumerate members whose name is ProcessStatusEnum: SUCCESS / UNKNOWN_REASON.
If you do not use enumerations
Before enumerations were born, that is, before JDK 1.5, we usually used int constants to represent enumerations, with the following code:
Public static final int COLOR_RED = 1; public static final int COLOR_BLUE = 2; public static final int COLOR_GREEN = 3
However, there may be two problems with using the int type:
First, the int type itself is not secure. If a programmer defines int without a final keyword, there is a risk that it will be modified by someone else. In contrast, the enumerated class is a constant class "naturally" and there is no risk of being modified (see the second half for reasons). Second, the semantics of using the int type are not clear enough. For example, if we only output a number like 1. 2. 3 when printing on the console, we certainly don't know what it means.
Then someone said, then use constant characters, it is not that you do not know the semantics, do you? The sample implementation 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. Some junior programmers will not follow the routine, and they may directly use the values of strings for comparison instead of enumerated fields. The sample implementation 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");}
In this way, when we modify the value in the enumeration, the program becomes cool.
Enumerate usage scenarios
A common use scenario for enumerations is a singleton, and its complete implementation code is as follows:
Public class Singleton {/ / enumerated types are thread-safe and will only be loaded once private enum SingletonEnum {INSTANCE; / / declare singleton object private final Singleton instance; / / instantiate 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 enumerations are loaded only once when the class is loaded, it is thread-safe, which is the main reason why "Effective Java" authors strongly recommend enumerations to implement singletons.
Knowledge expansion
Why are enumerations thread-safe?
Let's start with enumerating the resulting bytecode. First, let's 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 {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, we can see that the enumeration class will eventually be compiled into a normal class modified by final, and all its properties will be modified by the static and final keywords, so the enumeration class will be loaded and initialized by JVM when the project starts, and this execution process is thread-safe, so the enumeration class is also a thread-safe class.
Tip: the process of decompiling the code is to compile the bytecode (.class) of the java code with the javac command, and then use the javap command to view the compiled bytecode.
Tips for enumerating
We use = = when comparing enumerations, because enumerated classes are created when the program is loaded (it is not new), and enumerated classes do not allow direct external use of the new keyword to create enumerated instances, so we essentially have only one object when using enumerated classes, so using = = is sufficient for enumerated comparisons.
And when we look at the equlas () source code of the enumeration, we will find that the = = method is actually called directly inside it. The source code is as follows:
Public final boolean equals (Object other) {return this==other;} at this point, the study on "Why Java enumeration is recommended" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.