A detailed explanation of Java enum usage

Source: Internet
Author: User

Usage One: Constants

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.

enumSignal {GREEN, YELLOW, RED} Public classtrafficlight {Signal color=signal.red;  Public voidChange () {Switch(color) { CaseRed:color=Signal.green;  Break;  CaseYellow:color=signal.red;  Break;  CaseGreen: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 enumColor {RED ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); //member Variables        PrivateString name; Private intindex; //Construction Method        PrivateColor (String name,intindex) {             This. Name =name;  This. index =index; }        //Common Methods         Public StaticString GetName (intindex) {             for(Color c:color.values ()) {if(C.getindex () = =index) {                    returnC.name; }            }            return NULL; }        //Get Set Method         PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         Public intGetIndex () {returnindex; }         Public voidSetindex (intindex) {             This. index =index; }    }

Usage Four: Methods for overriding enumerations

An example of the ToString () method overlay is given below.

 Public classTest { Public enumColor {RED ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); //member Variables        PrivateString name; Private intindex; //Construction Method        PrivateColor (String name,intindex) {             This. Name =name;  This. index =index; }        //override Method@Override PublicString toString () {return  This. Index + "_" + This. Name; }    }     Public Static voidMain (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 InterfaceBehaviour {voidprint ();    String GetInfo (); }     Public enumColorImplementsbehaviour {RED ("Red", 1), Green ("green", 2), BLANK ("White", 3), Yello ("Yellow", 4); //member Variables        PrivateString name; Private intindex; //Construction Method        PrivateColor (String name,intindex) {             This. Name =name;  This. index =index; }        //interface Method@Override PublicString GetInfo () {return  This. Name; }        //interface Method@Override Public voidprint () {System.out.println ( This. Index + ":" + This. Name); }    }

Usage VI: Organizing enumerations using interfaces

 Public Interface Food {        enumimplements food {            black_coffee, Decaf_coffee, LATTE, Cappuccino        }         enum 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 classLight {/*Red light*/         Public Final Static intRED = 1; /*Green Light*/         Public Final Static intGREEN = 3; /*Yellow light*/         Public Final Static intYELLOW = 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 enumLight {//using the constructor function to pass parametersRED (1), GREEN (3), YELLOW (2); //Defining private Variables    Private intNCode; //constructor, the enumeration type can only be private    PrivateLight (int_ncode) {         This. NCode =_ncode; } @Override PublicString toString () {returnString.valueof ( This. NCode); }}

Third, complete Sample code

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&lt ;        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

Transferred from: https://www.cnblogs.com/happyPawpaw/archive/2013/04/09/3009553.html

A detailed explanation of Java enum usage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.