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

Summary of knowledge points related to enumeration in Java

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains the "Java enumeration-related knowledge points summary", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Java enumeration-related knowledge points summary"!

Enumerations in Java

Enumerations are usually a set of related collections of constants, and other programming languages have been using enumerations for a long time, such as C++. Starting with JDK1.5, Java also supports enumerated types.

Enumeration is a special data type, which is not only a class type, but also has more special constraints than class types. These constraints also create the simplicity, security and convenience of enumerated types.

In Java, enumerated types are declared through enum, which inherits from java.lang.Enum by default. So you can no longer inherit other classes when you declare an enumerated class.

Enumeration declaration

In life, we often identify directions, east, south, west and west, and their names, attributes, and so on are basically determined, and we can declare them as enumerated types:

Public enum Direction {EAST, WEST, NORTH, SOUTH;}

Similarly, seven days a week can be declared as an enumerated type:

Enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}

In the absence of enumerations or the use of enumerations, it does not mean that variables cannot be defined, we can define constants through classes or interfaces:

Public class Day {public static final int MONDAY = 1; public static final int TUESDAY=2; public static final int WEDNESDAY=3; public static final int THURSDAY=4; public static final int FRIDAY=5; public static final int SATURDAY=6; public static final int SUNDAY=7;}

However, there are many shortcomings, such as type safety and ease of use. If there are variables that define the same int value, the probability of confusion is high, and the compiler will not give any warning. Therefore, this method of writing is not recommended when enumerations can be used.

The underlying implementation of the enumeration

As we have said above, enumerations are a special class, and each enumerated item is essentially an instance of the enumerated class itself.

Therefore, the above enumeration class Direction can be exemplified by the following code:

Final class Direction extends Enum {public final static Direction EAST = new Direction (); public final static Direction WEST = new Direction (); public final static Direction NORTH = new Direction (); public final static Direction SOUTH = new Direction ();}

First compile the Direction with the javac command, and then check the contents of the corresponding class file with the javap command:

Bogon:enums apple$ javap Direction.class Compiled from "Direction.java" public final class com.choupangxia.enums.Direction extends java.lang.Enum {public static final com.choupangxia.enums.Direction EAST; public static final com.choupangxia.enums.Direction WEST; public static final com.choupangxia.enums.Direction NORTH; public static final com.choupangxia.enums.Direction SOUTH; public static com.choupangxia.enums.Direction [] values (); public static com.choupangxia.enums.Direction valueOf (java.lang.String); static {};}

As you can see, after being compiled by the compiler, an enumeration becomes an abstract class, it inherits the java.lang.Enum; and the enumeration constant defined in the enumeration becomes the corresponding public static final property, and its type is the type of the abstract class, and the name is the name of the enumeration constant.

Enumerate usage instances

From the decompilation above, we can see that the option of an enumeration is essentially a variable of public static final, so just use it as such a variable.

Public class EnumExample {public static void main (String [] args) {Direction north = Direction.NORTH; System.out.println (north); / / Prints NORTH}}

The ordinal () method of enumeration

The ordinal () method is used to get the order in which enumerated variables are declared in the enumeration class, with subscripts starting at 0, similar to subscripts in an array. It is designed for the use of complex enumeration-based data structures in EumSet and EnumMap.

Direction.EAST.ordinal (); / / 0 Direction.NORTH.ordinal (); / / 2

It is important to note that if the location of the enumerated item declaration changes, so does the value of the ordinal method. So, come in and avoid using this method. Otherwise, when there are more enumerated items, others add or delete one item in the middle, which will lead to all subsequent order changes.

Values () and valueOf () of enumerations

The values () method takes all the variables in the enumerated class and returns as an array:

Direction [] directions = Direction.values (); for (Direction d: directions) {System.out.println (d);} / / Output: EAST WEST NORTH SOUTH

The values () method is a static method that the compiler inserts into the enumerated class, but it does not exist in its parent class, Enum.

The valueOf (String name) method, like the valueOf method in the Enum class, is similar to getting enumerated variables by name, and is also generated by the compiler, but it is more concise, passing only one parameter.

Direction east = Direction.valueOf ("EAST"); System.out.println (east); / / Output: EAST

Enumeration naming convention

By convention, enumerations are constant, so the style of all uppercase and underscore separation (UPPER_CASE) is adopted. That is, enumerated class names are the same as normal class conventions, while variables in enumerations are consistent with static variable naming conventions.

Construction method of enumeration

By default, enumerated classes do not require constructors, and the default variable is the string at the time of declaration. Of course, you can also initialize some state information of enumerations by customizing the constructor. Typically, we pass in two parameters in the construction parameters, for example, an encoding and a description.

Take the above direction as an example:

Public enum Direction {/ / enum fields EAST (0), WEST (180), NORTH (90), SOUTH (270); / / constructor private Direction (final int angle) {this.angle = angle;} / / internal state private int angle; public int getAngle () {return angle;}}

If we want to access the angle in each direction, we can use a simple method call:

Direction north = Direction.NORTH; System.out.println (north) / / NORTH System.out.println (north.getAngle ()); / / 90 System.out.println (Direction.NORTH.getAngle ()); / / 90

Methods in enumeration

Enumerations are a special class, so you can have methods and properties like ordinary classes. In enumerations, you can declare not only specific methods, but also abstract methods.

The access permissions for methods can be private, protected, and public. You can use these methods to return the value of the enumerated item, or you can do some internal private processing.

Public enum Direction {/ / enum fields EAST, WEST, NORTH, SOUTH; protected String printDirection () {String message = "You are moving in" + this + "direction"; System.out.println (message); return message;}}

The use of the corresponding method is as follows:

Direction.NORTH.printDirection (); Direction.EAST.printDirection ()

Abstract methods can also be defined in enumerated classes, but the corresponding abstract methods must be implemented in each enumerated item:

Public enum Direction {/ / enum fields EAST {@ Override public String printDirection () {String message = "You are moving in east. You will face sun in morning time. "; return message;}}, WEST {@ Override public String printDirection () {String message =" You are moving in west. You will face sun in evening time. "; return message;}}, NORTH {@ Override public String printDirection () {String message =" You are moving in north. You will face head in daytime. "; return message;}}, SOUTH {@ Override public String printDirection () {String message =" You are moving in south. Sea ahead. "; return message;}; public abstract String printDirection ();}

The call to an abstract method is the same as a normal method:

Direction.NORTH.printDirection (); Direction.EAST.printDirection ()

In this way, you can easily define the different behavior of each enumerated instance. For example, you can define such an abstract method if you need each enumerated item to print the name of the direction.

The above instance enum class seems to be polymorphic, but unfortunately an instance of an enumerated type cannot be used as a type pass after all. The compiler fails in the following ways:

/ / failed to compile. Direction.NORTH is an instance object public void text (Direction.NORTH instance) {}

Inheritance of enumerations

As mentioned above, enumerations inherit from java.lang.Enum,Enum is an abstract class:

Public abstract class Enum implements Comparable, Serializable {/ /...}

That is, all enumerated classes support the features of Comparable and Serializable. It is also because all enumerated classes inherit Enum, so you can no longer inherit other classes, but you can implement interfaces.

Comparison of enumerations

All enumerations are Comparable and singleton by default, so you can compare them through the equals method, or even directly with the double equal sign "= =".

Direction east = Direction.EAST; Direction eastNew = Direction.valueOf ("EAST"); System.out.println (east = = eastNew); / / true System.out.println (east.equals (eastNew)); / / true

Enumerated collections: EnumSet and EnumMap

Two enumerated collection classes are introduced under the java.util package: EnumSet and EnumMap.

EnumSet

The EnumSet class is defined as follows:

Public abstract class EnumSet extends AbstractSet implements Cloneable, java.io.Serializable {/ /...}

EnumSet is a dedicated Set collection used with enumerated types, and all elements in the EnumSet must be enumerated types. Unlike other Set interface implementation classes HashSet/TreeSet, the internal implementation of EnumSet is a bit vector.

Bit vector is a very efficient bit operation. Because both direct storage and operation are bit, the space and time performance of EnumSet is considerable, which is comparable to the traditional "bit flag" operations based on int. The key is that we can operate bit operations like set sets.

EnumSet does not allow the use of null elements. Trying to insert null will throw NullPointerException, but testing to determine whether there is a null element or removing null elements will not throw an exception. Like most Collection implementations, EnumSet is not thread-safe, and you should pay attention to data synchronization in a multi-threaded environment.

Examples of use:

Public class Test {public static void main (String [] args) {Set enumSet = EnumSet.of (Direction.EAST, Direction.WEST, Direction.NORTH, Direction.SOUTH);}}

EnumMap

EnumMap's statement is as follows:

Public class EnumMap extends AbstractMap implements java.io.Serializable, Cloneable {}

Similar to EnumSet, EnumMap is a special Map,Map whose Key must be an enumerated type. EnumMap is internally implemented through arrays, which is a little more efficient than normal Map. The key value of EnumMap cannot be null, and EnumMap is not thread-safe.

Examples of EnumMap usage are as follows:

Public class Test {public static void main (String [] args) {/ / Keys can be only of type Direction Map enumMap = new EnumMap (Direction.class); / / Populate the Map enumMap.put (Direction.EAST, Direction.EAST.getAngle ()); enumMap.put (Direction.WEST, Direction.WEST.getAngle ()); enumMap.put (Direction.NORTH, Direction.NORTH.getAngle ()); enumMap.put (Direction.SOUTH, Direction.SOUTH.getAngle ());}}

Enumeration and switch

When using switch for condition judgment, the condition parameters can only be integer and character type, and enumerated type is also supported. Switch also supports strings after java7.

Examples of use are as follows:

Enum Color {GREEN,RED,BLUE} public class EnumDemo4 {public static void printName (Color color) {switch (color) {/ / there is no need to use Color to reference case BLUE: System.out.println ("blue"); break; case RED: System.out.println ("red"); break Case GREEN: System.out.println (green); break;}} public static void main (String [] args) {printName (Color.BLUE); printName (Color.RED); printName (Color.GREEN);}}

Enumeration and singleton

Singleton pattern is one of the most common design patterns in daily use. there are many ways to realize singleton pattern (hungry pattern, lazy pattern, etc.). We will not repeat it here, but only use the most common singleton as a control. and then see how to implement the singleton pattern based on enumeration.

The realization of the hungry model:

Public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}}

Simple and straightforward, the disadvantage is that the instance may be created when it is not needed, which does not have the effect of lazy loading. The advantage is that it is easy to implement and safe and reliable.

For such a singleton scenario, if it is implemented through enumeration, it is as follows:

Public enum Singleton {INSTANCE; public void doSomething () {System.out.println ("doSomething");}}

According to effective java, the best singleton implementation pattern is the enumeration pattern. Taking advantage of the nature of enumerations, let JVM help us ensure thread safety and single instance problems. In addition, the writing method is also very simple.

It can be called directly through Singleton.INSTANCE.doSomething (). Convenient, simple and safe.

Thank you for your reading, the above is the "Java enumeration-related knowledge points summary" content, after the study of this article, I believe you on the Java enumeration-related knowledge points summary of this problem has a more profound experience, the specific use of the need for you to practice and verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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