Use of the Java enum type enum

Source: Internet
Author: User

When I recently discussed the issue with my colleagues, my colleague suddenly mentioned why the constant values defined in Java do not take the ENMU enumeration type and are defined by the public final static type. We used to be defined in this way, rarely using the enum definition, so also did not pay attention to, in the face of the problem, it is still a little unclear why there is such a definition. If you don't understand, take the time to study it.

Enum types in Java are defined by the keyword enum, a new type from jdk1.5, and all enum types inherit from the enum type. To understand enumeration types, we recommend that you first open the Enum class in the JDK and simply read it, which defines a lot of protected methods, such as constructors, that we can use to define enum types in the current class. Each enumeration type has its own name and order, and when we output an enumeration type, we enter the name of the enumeration type, which can be referred to in the following example.

One, usually defines the 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.

package com.csdn.myEnum;public class Light {    /* 红灯 */    public final static int RED =1;    /* 绿灯 */    public final static int GREEN =3;    /* 黄灯 */    public final static int YELLOW =2;}

Second, enumeration type defines the constant method

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 {       // 利用构造函数传参       RED (1), GREEN (3), YELLOW (2);       // 定义私有变量       private int nCode ;       // 构造函数,枚举类型只能为私有       private Light( int _nCode) {           this . nCode = _nCode;       }       @Override       public String toString() {           return String.valueOf ( this . nCode );       }    }

Three, complete sample code

The full demo code for the enumeration type is as follows:

Package Com.csdn.myenum;import Java.util.enummap;import Java.util.enumset;public class Lighttest {//1. Defining enumeration Types Publ       IC enum Light {//Use the constructor to pass a parameter RED (1), GREEN (3), YELLOW (2);       Defines a private variable, private int nCode;       Constructor, the enumeration type can be private only (int _ncode) {this. NCode = _ncode;       } @Override Public String toString () {return string.valueof (this. nCode);  }}/** * @param args */public static void main (string[] args) {//1. Iterate through enumeration type System. Out       . println ("Demo enumeration type traversal ...");       Testtraversalenum (); 2. Demonstrates the use of the System for Enummap objects.       Out. println ("demonstrates the use and traversal of Enmumap objects ...");       Testenummap (); 3. Demonstrates the use of the Enmuset System.       Out. println ("demonstrates the use and traversal of Enmuset objects ...");    Testenumset ();       }/** * Demonstrates enumeration type Traversal */private static void Testtraversalenum () {light[] alllight = Light.values (); For (Light Alight:allligHT) {System. println ("Current lamp name:" + alight.name ()); System.           Out. println ("Current lamp ordinal:" + alight.ordinal ()); System.       Out. println ("Current light:" + 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 arguments to pass in, default is the type of the key class Enummap<light, string> currenummap = new E       Nummap<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. 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. println ("Data in current Enumset:" + 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

Iv. common definitions of constant methods and enumerations 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 doesn't see the code doesn't know what you're trying to do, discard all your old public static final constants.

    1. 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

    1. The switch () parameter can use enum

    2. 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

    3. Subclasses cannot be inherited from an enum, and if an element in an enum needs to be extended, an enumeration that implements that interface is created inside an interface to group the elements. The enumeration elements are grouped to be reached.

    4. Use Enumset instead of flags. An enum requires that its members are unique, but the add element cannot be removed from the enum.

    5. The Enummap key is an enum, and value is any other object.

    6. Enum allows programmers to write methods for EUNM instances. Therefore, each enum instance can be given a different behavior.

    7. Use the Enum's responsibility chain (Chain of Responsibility). This is related to the design pattern of responsibility chain mode. 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.

    8. State machine using enum

    9. Using the enum multi-channel distribution

Use of the Java enum type enum

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.