Before JDK1.5, we defined constants: public static fianl ..... Now, with enumerations, you can group related constants into an enumeration type, and enumerations provide more methods than constants.
public enum Color { RED, GREEN, BLANK, YELLOW
Usage Two: Switch
The switch statement before JDK1.6 only supports int,char,enum types, and using enumerations can make our code more readable.
Enum Signal { GREEN, YELLOW, RED } public class TrafficLight { Signal color = signal.red; public void Change () { switch (color) {case RED: color = signal.green; break; Case YELLOW: color = signal.red; break; Case GREEN: color = signal.yellow; Break;}}}
Usage Three: Add a new method to the enumeration
If you intend to customize your own method, you must add a semicolon at the end of the enum instance sequence. And Java requires that an enum instance be defined first.
public enum Color ( "Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); Member variable private String name; private int index; Construction Method Private Color (String name, int index) { this.name = name; This.index = index; } Normal method public static String getName (int index) {for (Color c:color.values ()) { if (c.getindex () = = Inde x) { return c.name; } } return null; } Get Set method public String GetName () { return name; } public void SetName (String name) { this.name = name; } public int GetIndex () { return index; } public void Setindex (int index) { this.index = index; } }
Usage Four: Methods for overriding enumerations
An example of the ToString () method overlay is given below.
public class Test {public enum Color {red ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); Member variable private String name; private int index; Construction Method Private Color (String name, int index) { this.name = name; This.index = index; } overriding method @Override public String toString () { return this.index + "_" + THIS.name; } } public static void Main (string[] args) { System.out.println (Color.RED.toString ());} }
Usage Five: Implement Interface
All enumerations are inherited from the Java.lang.Enum class. Because Java does not support multiple inheritance, enumeration objects can no longer inherit from other classes.
Public interface Behaviour { void print (); String getInfo (); } Public enum Color implements behaviour {red , 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); Member variable private String name; private int index; Construction Method Private Color (String name, int index) { this.name = name; This.index = index; } Interface method @Override public String getInfo () { return this.name; } Interface method @Override public void print () { System.out.println (This.index + ":" + this.name); } }
Usage VI: Organizing enumerations using interfaces
Public interface Food { enum Coffee implements food { Black_coffee, Decaf_coffee, LATTE, Cappuccino } Enum dessert implements Food { FRUIT, CAKE, GELATO } }
Usage Seven: About the use of enumeration collections
Java.util.EnumSet and Java.util.EnumMap are two enumeration collections. Enumset guarantees that the elements in the set are not duplicated; The key in Enummap is the enum type, and value can be any type. The use of this two collection is not here to repeat, you can refer to the JDK documentation
Differences between enumerations and constants definitions
First, typically define a constant method
We usually use the public final static method to define the code as follows, with 1 for the red Light, 3 for the green, and 2 for the yellow light.
public class Light {/ * red */public final static int RED = 1; /* green light */public final static int GREEN = 3; /* YELLOW light */public final static int YELLOW = 2; }
Second, Enumeration types define constant methods
The simple definition of enum types is as follows, and we don't seem to be able to define values for each enum 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 show the red, green and yellow lights, but we can't show the exact value. Don't worry, since enumeration types provide constructors, we can do this through constructors and the override of the ToString method. The constructor is added to the light enumeration type first, and then the value of each enumeration type is passed through the constructor to the corresponding parameter, and the ToString method is used to return the parameters passed in from the constructor, and the modified code is as follows:
Public enum Light { //Use the constructor to pass the parameter RED (1), GREEN (3), YELLOW (2); Defines a private variable , private int nCode; Constructor, the enumeration type can be private only light (int _ncode) { this.ncode = _ncode; } @Override public String toString () { return string.valueof (This.ncode);} }
Third, complete Sample code
The full demo code for the enumeration type is as follows:
public class Lighttest {//1. Defining enum type Public enum light {//using the constructor to pass the parameter RED (1), GREEN (3), YELLOW (2); Defines a private variable, private int nCode; Constructor, the enumeration type can be private only light (int _ncode) {this.ncode = _ncode; } @Override Public String toString () {return string.valueof (This.ncode); }}/** * * @param args */public static void main (string[] args) {//1. Traversing enumeration type System . OUT.PRINTLN ("Demo enumeration type traversal ..."); Testtraversalenum (); 2. Demonstrate the use of the Enummap object System.out.println ("Demo Enmumap object usage and traversal ..."); Testenummap (); 3. Demonstrate the use of the Enmuset System.out.println ("Demo Enmuset object usage and traversal ..."); Testenumset (); }/** * * Demo Enumeration type Traversal */private static void Testtraversalenum () {light[] alllight = light.values (); for (light alight:alllight) {System.out.println ("Current lamp name:" + alight.name ()); System.out. println ("Current lamp ordinal:" + alight.ordinal ()); SYSTEM.OUT.PRINTLN ("Current lamp:" + alight); }}/** * * Demonstrates the use of Enummap, Enummap is similar to the use of HashMap, except that key is enumerated type */private static void Testenummap () { 1. Demo defines the Enummap object, the constructor of the Enummap object requires parameters to pass in, default is the type of the key class Enummap<light, string> currenummap = new Enummap< ; Light, string> (Light.class); Currenummap.put (light.red, "red light"); Currenummap.put (Light.green, "green light"); Currenummap.put (Light.yellow, "yellow Light"); 2. Traverse object for (Light ALight:Light.values ()) {System.out.println ("[key=" + alight.name () + ", value=" + currenummap.get (alight) + "]"); }}/** * * Demonstrates how enumset is used, Enumset is an abstract class that gets a type of enum type content <BR/> * * Can use the AllOf method */Private static void Testenumset () {enumset<light> currenumset = Enumset.allof (Light.class); for (light alightsetelement:currenumset) {System.out.println ("current enThe data in Umset is: "+ alightsetelement); } }}
The results of the implementation are as follows:
Demonstrates the traversal of enumeration types ...
Current Lamp name:red
Current Lamp ordinal:0
Current lamp: 1
Current Lamp Name:green
Current Lamp ordinal:1
Current lamp: 3
Current Lamp Name:yellow
Current Lamp Ordinal:2
Current lamp: 2
Demonstrates the use and traversal of Enmumap objects .....
[Key=red,value= Red]
[Key=green,value= green light]
[Key=yellow,value= Yellow Light]
Demonstrates the use and traversal of Enmuset objects .....
The data in the current Enumset is: 1
The data in the current Enumset is: 3
The data in the current Enumset is: 2
Four, typically define constant methods and enumerations to define constant method differences
The following may be a bit boring, but definitely worth a glimpse
1. Code:
public class State {public static final int on = 1;public static final int off= 0;}
What's wrong, everyone has been so used for a long time, no problem ah.
First, it is not type-safe. You have to make sure it's int.
Second, you have to make sure it's 0 and 1.
Finally, many times when you print out, you only see 1 and 0,
But the person who does not see the code does not know your intentions, discarding all of your old public static final constants
2. You can create an enum class that is considered an ordinary class. Except that it cannot inherit other classes. (Java is a single inheritance, it has inherited an enum),
You can add other methods that override the method of its own
3. The switch () parameter can use enum
4. The values () method is the static method that the compiler inserts into the enum definition, so when you convert an enum instance up to a parent enum, values () is inaccessible. Workaround: There is a getenumconstants () method in class, so even if the enum interface does not have the values () method, we can still get all the enum instances through the class object
5. You cannot inherit subclasses from an enum, and if you need to extend the elements in an enum, within an interface, create an enumeration that implements that interface to group the elements. The enumeration elements are grouped to be reached.
6. Use Enumset instead of logo. An enum requires that its members are unique, but the add element cannot be removed from the enum.
7. Enummap key is Enum,value is any other object.
8. Enum allows programmers to write methods for EUNM instances. Therefore, each enum instance can be given a different behavior.
9. Use the Enum's responsibility chain (Chain of Responsibility). This is related to the design pattern of the responsibility chain model. Solve a problem in a number of different ways. Then link them together. When a request arrives, it traverses the chain until a solution in the chain can handle the request.
10. State machine using enum
11. Using the enum multi-channel distribution
A detailed explanation of Java enum usage