Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Knowledge of Java enumeration class is explained in detail

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is "detailed explanation of Java enumeration knowledge". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Java enumeration knowledge detailed explanation" bar!

The enum type, a new feature in Java 5, allows specific pieces of data to be represented in constants, all in a type-safe form.

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 enumeration type is a collection of possible values for a certain type of data, for example, the collection of possible values for the week of the week is:

{Sun,Mon,Tue,Wed,Thu,Fri,Sat}

The collection can be defined as an enumerated type that describes the week, and there are seven elements in the enumerated type, so enumerated variables defined with enumerated types can take only one 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 an enumerated type, you can also specify the integer constant value for the element.

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.

Can inherit multiple interfaces

Can have constructors, member methods, member variables

1.2 differences between enumerated classes and 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 the methods of this class

Here is an example of an override by 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

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;} implementation principle 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 enumeration constants defined by the enumerated type.

The values method added by the compiler:

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.

Enumerated actual combat without participation.

(1) define an enumerated class without parameters

Enum SeasonType {SPRING, SUMMER, AUTUMN, WINTER}

(2) use in actual combat

/ / choose the following usage according to the actual situation, you can SeasonType springType = SeasonType.SPRING; / / output SPRING String springString = SeasonType.SPRING.toString (); / / output SPRING actual combat 2 has one parameter

(1) define an enumerated class with only one parameter

Enum SeasonType {/ / pass parameters through the constructor and create instances SPRING ("spring"), SUMMER ("summer"), AUTUMN ("autumn"), WINTER ("winter"); / / define the parameters corresponding to the instance private String msg; / / required: create an instance SeasonType (String msg) {this.msg = msg for enumerated values through this constructor } / / the parameter value public String getMsg () {return msg;}} of the corresponding instance can be obtained by this method

(2) use in actual combat

/ / when we assign a value to an instance class, we can use the following way: String msg = SeasonType.SPRING.getMsg (); / / output spring practice 3 has two parameters

(1) define an enumerated class with two parameters

Public enum Season {/ / pass parameters through the constructor and create instances SPRING (1, "spring"), SUMMER (2, "summer"), AUTUMN (3, "autumn"), WINTER (4, "winter"); / / define the parameter private Integer key; private String msg corresponding to the instance / / required: create an instance of Season (Integer key, String msg) {this.key = key; this.msg = msg for enumerated values through this constructor } / / in many cases, the value we get from the front end is the key of the enumerated class, and then we can get the corresponding enumerated value public static Season valueofKey (Integer key) {for (Season season: Season.values ()) {if (season.key.equals (key)) {return season) by the following static method }} throw new IllegalArgumentException ("No element matches" + key);} / / the key value public Integer getKey () {return key;} / / the msg value public String getMsg () {return msg;}} of the corresponding instance can be obtained by this method

(2) use in actual combat

/ / output enumerated value instance Season season = Season.valueofKey (1) with key 1; / output keyInteger key = Season.SPRING.getKey () corresponding to SPRING instance; / / output msgString msg = Season.SPRING.getMsg () corresponding to SPRING instance; enumerate class summary

In fact, after the enumeration class understands its concept, enumeration becomes quite simple, and you can write an enumeration class at will. Therefore, as in the previous few practical examples, we must first clarify the concept, and then practice it a few times before ok.

I'll repeat the important concepts here to help brothers master this piece of knowledge quickly. first of all, remember that enumerated values in enumerated classes can have no parameters or multiple parameters, and each enumerated value is an instance.

And it is also important that if the enumerated value has n parameters, then there must be n parameter values in the constructor, because each enumerated value declared will call the constructor to create an instance, so the parameters must correspond one to one. Now that we understand this, we just need to define the n parameters as n member variables in the enumeration class, then provide the corresponding get () method, and then we can get any parameter values in the instance at will through the instance.

If you want to make the enumeration class easier to use, you can imitate what I wrote in practice 3, through a certain parameter value, such as the key parameter value, you can get its corresponding enumeration value, and then get whatever value you want.

Enumerate API

All the enumerated classes we define using enum inherit the java.lang.Enum class, so we inherit its API. The common API is as follows:

String name ()

Get enumeration name

Int ordinal ()

Gets the position of the enumeration (subscript, initial value is 0)

Valueof (String msg)

Get its corresponding enumerated type through msg. (for example, enumeration classes or other enumeration classes in practice II are fine, as long as they are used properly)

Values ()

Get all the enumerated values in the enumeration class (for example, used in practice 3)

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.

At this point, I believe you have a deeper understanding of the "detailed explanation of Java enumeration knowledge". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report