Java enum type enum

Source: Internet
Author: User

Simple Introduction

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.WBG; Public classLight {/*Red light*/     PublicFinalStatic intRED =1; /*Green Light*/     PublicFinalStatic intGREEN =3; /*Yellow light*/     PublicFinalStatic intYELLOW =2;}
second, enumeration type defines the constant method

Enumeration types provide constructors that can be implemented by constructors and by 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 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 (intNCode) {            This. NCode =NCode; } @Override PublicString toString () {returnString.valueof ( This. NCode); }    }
Three, complete sample code

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

Package COM.WBG, import java.util.enummap;import java.util.EnumSet, public class Lighttest {//1. Define enum type Public enum Light {//use the constructor to pass a reference to 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 () {returnstring.valueof (this. nCode); }    }     /**      *@param args*/Public static void Main (string[] args) {//1. Traverse the enumeration type System. println ("demonstrates the traversal of enumeration types ..." );        Testtraversalenum (); //2. Demonstrates the use of the Enummap object using System. println ("demonstrates the use and traversal of Enmumap objects ....." );        Testenummap (); //3. Demo Enmuset using System. Out. println ("demonstrates the use and traversal of Enmuset objects ....." );    Testenumset (); }     /**      *to demonstrate the traversal of enumeration types*/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 lamp:"+alight); }    }     /**      *demonstrates the use of Enummap, Enummap is similar to HashMap, except that if key is enumerated type*/private static void Testenummap () {//1The . Demo defines the Enummap object, the constructor of the Enummap object requires a parameter pass in, and the 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. Traversing an 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 an enumerated type of type content <BR/> *You can use the AllOf method*/private static void Testenumset () {Enumset<Light> Currenumset =Enumset.allof (light Class);  for(Light alightsetelement:currenumset) {System. println ("The data in the current Enumset is:"+alightsetelement); }     }}
View Code

The results of the implementation are as follows:

Iv. common definitions of constant methods and enumerations define constant method differences

1. Code:

 Public class State {publicstaticfinalint on = 1;  Public Static final int off= 0;}

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.

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 to override its own methods

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 an enum, and value is any of the other object objects.

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

10. State machine using enum

11. Using the enum multi-channel distribution

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.