In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "the grammar and specific use of the Java enumeration class". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
A preliminary study of enumerating classes
In programming, a set of several limited data elements is sometimes used, such as a collection of seven data elements from Monday to Sunday in a week, a set of three colors of red, yellow and green, a collection of ten employees in a work group, and so on. The value of a variable in the program is limited to the elements in the set. At this point, these data collections can be defined as enumerated types.
Therefore, an enumerated type is a collection of possible values of a certain type of data. For example, the collection of possible values of the week within a week is: {Sun,Mon,Tue,Wed,Thu,Fri,Sat} . This set can be defined as an enumerated type that describes the week. The enumerated type has seven elements, so enumerated variables defined by enumerated types can only take a certain element value in the collection. Because enumerated types are exported data types, you must define enumerated types before you define enumerated variables with enumerated types.
Enum {}; where the keyword enum means that enumerated types are defined, enumerated type names consist of identifiers, and enumerated element tables consist of enumerated elements or enumerated constants. For example: enum weekdays {Sun,Mon,Tue,Wed,Thu,Fri,Sat}; defines an enumerated type called weekdays, which contains seven elements: Sun, Mon, Tue, Wed, Thu, Fri, Sat.
When the compiler compiles the program, each element in the enumerated type is assigned an integer constant value (also known as an ordinal value). If the integer constant value of the element is not specified in the enumeration type definition, the integer constant value increases successively from 0, so the integer constant values of the seven elements Sun, Mon, Tue, Wed, Thu, Fri, and Sat of the weekdays enumerated type are 0, 1, 2, 3, 4, 5, 6, respectively. Note: when defining enumerated types, you can also specify integer constant values for elements.
For example, the enumerated type boolean that describes the logical value set {TRUE, FALSE} can be defined as follows: enum boolean {TRUE=1, FALSE=0}; this definition states that the value of TRUE is 1 and the value of FALSE is 0. the enumeration type colors that describes the color set {red,blue,green,black,white,yellow} can be defined as follows: enum colors {red=5,blue=1,green,black,white,yellow}; this definition specifies that red is 5 and blue is 1, and then the element value increases by 1 from 2. The values of green, black, white and yellow were 2, 3, 4 and 5, respectively.
at this point, the integer 5 will be used to represent the two colors red and yellow. It usually makes no sense for two different elements to have the same integer value. The definition of an enumerated type only defines a new data type, which can be used only if enumerated variables are defined with enumerated types.
Enumerated classes-syntax
Enum has the same status as class and interface; it can inherit multiple interfaces; it can have constructors, member methods and member variables; 1.2 enumerated classes are different from ordinary classes
Inherits the java.lang.Enum class by default, so it cannot inherit other parent classes; the java.lang.Enum class implements the java.lang.Serializable and java.lang.Comparable interfaces
Using enum definitions and final decorations by default, so you cannot derive subclasses
Constructors use private decorations by default, and can only use private decorations
All instances of the enumerated class must be given in the first line, with public static final modification added by default, otherwise the instance cannot be generated.
Specific use of enumerated classes
This section refers to https://blog.csdn.net/qq_27093465/article/details/52180865.
Constant public class constant {} enum Color {Red, Green, Blue, Yellow} switch
The switch statements before JDK1.6 only support int,char,enum types. Using enumerations can make our code more readable.
Public static void showColor (Color color) {switch (color) {case Red: System.out.println (color); break; case Blue: System.out.println (color); break; case Yellow: System.out.println (color); break Case Green: System.out.println (color); break;}} add a new method to the enumeration
If you plan to customize your own methods, you must add a semicolon at the end of the sequence of enum instances. And Java requires that the enum instance must be defined first.
Enum Color {/ / each color is an instance of the enumerated class, and the constructor should match the format of the enumerated class. / / if there is something else after the instance, add a semicolon at the end of the instance sequence. Red ("red", 1), Green ("green", 2), Blue ("blue", 3), Yellow ("yellow", 4); String name; int index; Color (String name, int index) {this.name = name; this.index = index;} public void showAllColors () {/ / values is an array of Color instances, which can be obtained through index and name. For (Color color: Color.values ()) {System.out.println (color.index + ":" + color.name);} overrides the enumeration method
All enumerated classes inherit from the Enum class, so you can override this class's methods with an example of overriding the toString () method.
@ Overridepublic String toString () {return this.index + ":" + this.name;} implement the interface
All enumerations inherit from the java.lang.Enum class. Because Java does not support multiple inheritance, enumerated objects can no longer inherit other classes.
Enum Color implements Print {@ Override public void print () {System.out.println (this.name);}} organizes enumerations using interfaces
Create an implementation interface to organize enumerations, which, in short, is classification. If you use a lot of enumerations, doing so makes it easy to call when writing code.
Public class uses interfaces to organize enumerations {public static void main (String [] args) {Food cf = chineseFood.dumpling; Food jf = Food.JapaneseFood.fishpiece; for (Food food: chineseFood.values ()) {System.out.println (food);} for (Food food: Food.JapaneseFood.values ()) {System.out.println (food) } interface Food {enum JapaneseFood implements Food {suse, fishpiece}} enum chineseFood implements Food {dumpling, tofu} enumerated class collection
Java.util.EnumSet and java.util.EnumMap are two enumerated collections. EnumSet guarantees that the elements in the collection are not duplicated; key in EnumMap is of type enum, while value can be of any type.
EnumSet did not find the implementation class in JDK. Here is an example of EnumMap
Collection of public class enumerated classes {public static void main (String [] args) {EnumMap map = new EnumMap (Color.class); map.put (Color.Blue, "Blue"); map.put (Color.Yellow, "Yellow"); map.put (Color.Red, "Red"); System.out.println (map.get (Color.Red));} considerations for using enumerated classes
Cdn.xitu.io/2019/4/7/169f6cd0645e7113?w=1144&h=154&f=png&s=81857 ">
Comparison of values between enumerated types of objects, you can use = = to compare values directly, whether they are equal, it is not necessary to use the equals method.
Because the enumeration class Enum has overridden the equals method
/ * * Returns true if the specified object is equal to this * enum constant. * * @ param other the object to be compared for equality with this object. * @ return true if the specified object is equal to this * enum constant. * / public final boolean equals (Object other) {return this==other;} underlying principles of enumerated classes
Refer to https://blog.csdn.net/mhmyqn/article/details/48087247 for this part.
Java supports enumerations starting with JDK1.5, that is, Java does not support enumerations at first, just like generics, which are new features added by JDK1.5. Usually, if a feature is not provided at the beginning and added later in the language development, you will encounter a problem, that is, the problem of backward compatibility.
Like many features introduced by Java in 1.5, for backward compatibility, the compiler will do a lot of things for us to write the source code, such as why generics erase types, why they generate bridging methods, foreach iterations, automatic boxing / unboxing, etc. There is a term called "syntax sugar", and the special processing of the compiler is called "paraphrase sugar". So enumerations like enumerations are also introduced in JDK1.5, and how are they implemented?
Java added the java.lang.Enum abstract class in 1. 5, which is the base class for all enumerated types. Provides some basic properties and basic methods. At the same time, support is provided for using enumerations as Set and Map, that is, java.util.EnumSet and java.util.EnumMap.
Next, define a simple enumeration class
Public enum Day {MONDAY {@ Override void say () {System.out.println ("MONDAY");}}, TUESDAY {@ Override void say () {System.out.println ("TUESDAY") }, FRIDAY ("work") {@ Override void say () {System.out.println ("FRIDAY");}}, SUNDAY ("free") {@ Override void say () {System.out.println ("SUNDAY");}}; String work / / when there are no construction parameters, each instance can be regarded as a constant. / / when using construction parameters, each instance will become different and can be regarded as a different type, so a class corresponding to the number of instances will be generated after compilation. Private Day (String work) {this.work = work;} private Day () {} / / the enumerated instance must implement the abstract method abstract void say () in the enumerated class;}
Decompilation result
D:\ MyTech\ out\ production\ MyTech\ com\ javase\ enumerated classes > javap Day.classCompiled from "Day.java" public abstract class com.javase. Day extends java.lang.Enum {public static final com.javase. Day MONDAY; public static final com.javase. Day TUESDAY; public static final com.javase. Day FRIDAY; public static final com.javase. Day SUNDAY; java.lang.String work; public static com.javase. Enumerated class. Day [] values (); public static com.javase. Day valueOf (java.lang.String); abstract void say (); com.javase. Enumerated class. Day (java.lang.String, int, com.javase. Enumerated class. Day $1); com.javase. Enumerated class. Day (java.lang.String, int, java.lang.String, com.javase. Enumerated class .Day $1); static {};}
As you can see, an enumeration becomes an abstract class after being compiled by the compiler, it inherits the enumeration constant defined in the java.lang.Enum; and becomes the corresponding public static final attribute, and its type is the type of the abstract class, and the name is the name of the enumeration constant.
At the same time, we can see the .class files com/mikan/Day$1.class, com/mikan/Day$2.class, com/mikan/Day$3.class and com/mikan/Day$4.class of the four inner classes under the same path of Operator.class, that is to say, these four named fields are implemented by the inner class respectively; at the same time, two methods values () and valueOf (String) are added; the constructor we defined originally has only one parameter, but it has become three parameters. At the same time, a static code block is generated. Take a closer look at these details next.
Let's take a look at the parts of the bytecode, where:
InnerClasses: static # 23; / / class com/javase/ enumerated class / Day$4 static # 18; / / class com/javase/ enumerated class / Day$3 static # 14; / / class com/javase/ enumerated class / Day$2 static # 10; / / class com/javase/ enumerated class / Day$1
You can see that it has four inner classes, and the details of these four inner classes will be analyzed later.
Static {} Descriptor: () V flags: ACC_STATIC Code: stack=5, locals=0 Args_size=0 0: new # 10 / / class com/javase/ enumerated class / Day$1 3: dup 4: ldc # 11 / / String MONDAY 6: iconst_0 7: invokespecial # 12 / / Method com/javase/ enumerated class / Day$1. "": (Ljava/lang/String I) V 10: putstatic # 13 / / Field MONDAY:Lcom/javase/ enumerated classes / Day 13: new # 14 / / class com/javase/ enumerated class / Day$2 16: dup 17: ldc # 15 / / String TUESDAY 19: iconst_1 20: invokespecial # 16 / / Method com/javase/ enumerated class / Day$2. "": (Ljava/lang/String;I) V / / is similar, omitted here}
In fact, the static code block generated by the compiler does the following work: setting the values of the four generated public static constant fields respectively, and the compiler also generates a static field $VALUES, which holds all the values methods added by the enumeration constant compiler for the enumeration type definition:
Public static com.javase.Day [] values (); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=0, args_size=0 0: getstatic # 2 / / Field $VALUES: [Lcom/javase/Day; 3: invokevirtual # 3 / / Method "[Lcom/mikan/Day;" .clone: () Ljava/lang/Object Checkcast # 4 / / class "[Lcom/javase/Day] "9: the areturn method is a public static method, so we can call the method (Day.values ()) directly to return an array of enumerated values. In addition, the implementation of this method is to clone the value of the $VALUES field initialized in the static code block and force the type to Day [] type return.
Why does the manufacturing method add two parameters?
There is a problem, the constructor we clearly defined only one parameter, why the generated constructor is three parameters?
We can see from the Enum class that there are two properties defined for each enumeration, name and ordinal,name represent the names of the enumeration constants we defined, such as FRIDAY, TUESDAY, and ordinal is a sequence number that assigns an integer value according to the defined order, starting with 0. When the enumeration constant is initialized, the corresponding values are automatically set for initializing these two fields, so two parameters are added to the constructor. That is, the inner classes generated by the other three enumeration constants are basically the same, so I won't repeat them here.
We can see from the code of the Enum class that the defined name and ordinal properties are final, and most of the methods are final, especially clone, readObject, writeObject, these three methods and enumerations are initialized by static code blocks.
It ensures that enumeration types are immutable, and enumerations cannot be copied through cloning, serialization and deserialization, which ensures that an enumeration constant is only an instance, that is, a singleton, so it is recommended to use enumerations to implement singletons in effective java.
Summary
Enumerations are essentially implemented through ordinary classes, but the compiler handles them for us. Each enumerated type inherits from java.lang.Enum and automatically adds values and valueOf methods.
Each enumeration constant is a static constant field, implemented using an inner class that inherits the enumeration class. All enumeration constants are initialized by static code blocks, that is, during class loading.
In addition, by defining the three methods clone, readObject and writeObject as final, the implementation is to throw the corresponding exception. This ensures that each enumeration type and enumeration constant are immutable. You can take advantage of these two features of enumerations to implement thread-safe singletons.
This is the end of the introduction to the syntax and specific usage of the Java enumeration class. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.