Article source: blog.csdn.net/wgw33536324…
Blog.csdn.net/yechaodechu… \
Usage of the Java enumeration type enum
When I was discussing with my colleague recently, I suddenly asked why we use public final Static instead of enMU enumeration to define constant values in Java. In the past, we have used this way of definition, rarely enum definition, so we have not noticed, faced with a sudden problem, really a little unclear why there is such a definition. If you don’t understand, take the time to study it.
Enumeration types in Java are defined with the keyword enum. New from JDK1.5, all enumeration types inherit from enum types. To understand enumerated types, we recommend that you open the Enum class in the JDK and read it briefly. The Enum class has protected methods, such as constructors, that you can use to define enumerated types in your current class. Each enumeration type has its own name and order. When we print an enumeration type, we enter the name of the enumeration type, as shown in the following example.
1. Constant methods are usually defined
The code we normally define with the public Final Static method is as follows, with 1 for red, 3 for green, and 2 for yellow.
package com.csdn.myEnum;public classLight {/* Light */public final static int RED= 1; / * green * /public final static int GREEN= 3; / * yellow light * /public final static int YELLOW= 2; } |
---|
Enumeration types define constant methods
The simple way to define an enumeration type is as follows. It seems impossible to define the value of every enumeration type. For example, our code for defining red, green, and yellow lights might look like this:
public enum Light { RED , GREEN , YELLOW; } |
---|
We can only represent red, green, and yellow, but we can’t represent the values. Don’t worry, since enumerations provide constructors, we can implement them by using constructors and overwriting toString methods. We first add a constructor to the Light enumerated type, then pass the corresponding argument to the constructor for each enumerated type, overwriting the toString method, which returns the argument from the constructor. The modified code looks like this:
public enumLight {// use the constructor to pass argumentsRED (1), GREEN (3), YELLOW(2); // Define private variablesprivate intnCode ; // The enumeration type can only be privateprivate Light( int _nCode) { this . nCode = _nCode; } @Override public String toString() { return String.valueOf ( this. nCode ); }} |
---|
Complete sample code
The complete demonstration code for enumeration types is as follows:
package com.csdn.myEnum; import java.util.EnumMap;import java.util.EnumSet; public classLightTest {// 1. Define enumeration typespublic enumLight {// use the constructor to pass argumentsRED (1), GREEN (3), YELLOW(2); // Define private variablesprivate intnCode ; // The enumeration type can only be privateprivate Light( int _nCode) { this . nCode = _nCode; } @Override public String toString() { return String.valueOf ( this. nCode ); }} / * * *@param args */ public static voidMain (String[] args) {// 1. Iterate through the enumeration type System.out.println(” Demonstrates traversal of enumerated types……” );testTraversalEnum(a); // 2. Demonstrate how to use System in EnumMap.out.println(” demonstrates the use and traversal of the EnmuMap object…..” );testEnumMap(a); // 3. Demonstrate the use of System EnmuSet.out.println(” demonstrates the use and traversal of EnmuSet objects…..” );testEnumSet(a); } /** * demonstrates traversal of enumeration types */private static void testTraversalEnum() { Light[] allLight = Light.values(a);for (Light aLight : allLight) { System. out.println(” name: “+ aLight. Name ()); System.out.println(” ordinal: “+ aLight. Ordinal ()); System.out.println(” current light: “+ aLight); }} /** * to use EnumMap, EnumMap is similar to HashMap, except that the key is of the enumeration type */private static voidTestEnumMap () {// 1. Demonstrate how to define an EnumMap object. The constructor of the EnumMap object requires argumentsnew EnumMap<Light, String>( Light. class ); currEnumMap.put(Light. RED, “red light”); currEnumMap.put(Light.GREEN, “green light”); currEnumMap.put(Light.YELLOW, “yellow light”); // 2. Iterate over the objectfor (Light aLight : Light.values ()) { System. out.println( “[key=” + aLight.name() + “,value=” + currEnumMap.get(aLight) + “]” ); }} /** * to show how to use EnumSet, EnumSet is an abstract class, to obtain the contents of the enumeration type of a typeprivate static void testEnumSet() { EnumSet<Light> currEnumSet = EnumSet.allOf (Light. class ); for (Light aLightSetElement : currEnumSet) { System. out. Println (” Current EnumSet: “+ aLightSetElement); }}} |
---|
The result is as follows:
Demonstrates traversal of enumerated types…… Current light Name: RED Current light ordinal: 0 Current light: 1 Current light Name: GREEN Current light ordinal: 1 Current light: 3 Current light Name: YELLOW Current light ordinal: 2 Current light: 2 Demonstrate the use and traversal of the EnmuMap object….. [key=RED,value= RED][key=GREEN,value= GREEN][key=YELLOW,value= YELLOW] demonstrate the use and traversal of the EnmuSet object….. The current data in EnumSet is: 1 The current data in EnumSet is: 3 The current data in EnumSet is: 2 |
---|
4. The difference between defining constant methods in general and enumerating constant methods
The following may be a bit boring, but it’s definitely worth a peek
1. The code:
public class State {
public static final int ON = 1;
public static final Int OFF= 0;
}
What’s wrong with it? Everyone’s been using it for a long time. There’s nothing wrong with it.
First of all, it’s not type-safe. You have to make sure it’s int
Second, you have to make sure it has a range of 0 and 1
And finally, a lot of times when you print it out, you just see ones and zeros,
People who haven’t seen the code don’t know what you’re trying to do, so discard all of your old public static final constants
2. You can create an enum class and treat it as a normal class. It can’t inherit from any other class. (Java is single inheritance, it already inherits Enum),
You can add another method to override its own method
3. The switch() parameter can use enum
4. Values () is a static method that the compiler inserts into an enum definition, so when you cast an enum instance up to its parent enum, values() becomes inaccessible. Workaround: There is a getEnumConstants() method in Class, so even if there is no values() method on the Enum interface, we can still get all Enum instances through the Class object
5. You cannot subclass from an enum. If you need to extend the elements in an enum, create an enumeration inside an interface to group the elements. Achieves grouping of enumeration elements.
6. Use EnumSet to replace flags. An enum requires that its members be unique, but the added element cannot be deleted.
7. The key of EnumMap is enum, and the value is any other Object.
8. Enum allows programmers to write methods for EUNM instances. So you can assign different behaviors to each enum instance.
9. Use enum Chain of Responsibility. This relates to the chain of responsibility pattern of the design pattern. Solve a problem in many different ways. Then link them together. When a request comes in, traverse the chain until one of the solutions in the chain can handle the request.
10. Use the enum state machine
11. Use enum multi-route distribution
\