"Go" Java enumeration type use of enum

Source: Internet
Author: User

Original URL: http://blog.csdn.net/wgw335363240/article/details/6359614

Java enum-type enum use

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.

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.

Package com.csdn.myEnum;

Public class Light {

/* Red light */

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 {

Using the constructor function to pass parameters

RED (1), GREEN (3), YELLOW (2);

Defining private variables

Private int NCode;

Constructor, the enumeration type can only be private

Private 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:

Package com.csdn.myEnum;

import Java.util.EnumMap;

import Java.util.EnumSet;

Public class lighttest {

1. defining enum types

Public enum Light {

Using the constructor function to pass parameters

RED (1), GREEN (3), YELLOW (2);

Defining private variables

Private int NCode;

Constructor, the enumeration type can only be private

Private 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 types

System. out. println ("Demo enumeration type traversal ...");

Testtraversalenum ();

2. Demonstrating the use of Enummap objects

System. out. println ("demonstrates the use and traversal of Enmumap objects ...");

Testenummap ();

3. Demonstrating the use of Enmuset

System. out. println ("demonstrates the use and traversal of Enmuset objects ...");

Testenumset ();

}

/**

* Demonstration of 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 light:" + alight);

}

}

/**

* Demonstrates the use of Enummap, Enummap is similar to HashMap, except that if key is enumerated type

*/

Private Static void Testenummap () {

1. Demonstrates defining a Enummap object, the constructor of the Enummap object requires a parameter to pass in, and the default is the type of the key's 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 objects

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

* You can use the AllOf method

*/

Private Static void Testenumset () {

Enumset<light> Currenumset = Enumset. AllOf (Light. class );

for (Light Alightsetelement:currenumset) {

System. out. println ("Current Data in 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

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

"Go" Java enumeration type use of 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.