Java enum (enumeration) and javaenum

Source: Internet
Author: User

Java enum (enumeration) and javaenum

In actual programming, there are often such "datasets", their values are stable in the program, and the elements in the "dataset" are limited.

For example, seven data elements from Monday to Sunday constitute a "dataset" for a week, and four data elements for spring, summer, and autumn constitute a "dataset" for the Four Seasons ".

Enum is called enumeration. It is a new feature introduced in JDK 1.5 and is stored in the java. lang package. In this case, enum can be used. This is not only the purpose of enumeration types. For specific use cases, see the following introduction.

1. Constants

In the past, we defined a constant, usually using public static final ...... Defined as follows:

public static final CONSTANT_STR = "TEST";

Or use the variables defined by the interface, because the variables defined by the interface are all public static final by default, as follows:

/*** Constant interface of the week */public interface IWeekConstants {String MON = "Mon"; String TUE = "Tue"; String WED = "Wed "; string THU = "Thu"; String FRI = "Fri"; String SAT = "Sat"; String SUN = "Sun ";}

With enumeration, we can use the following method:

public enum WeekEnum {    MON, TUE, WED, THU, FRI, SAT, SUN;}

Explanation: To create an enumeration type, use the enum keyword, which implies that all created types are subclasses of the java. lang. Enum class (java. lang. Enum is an abstract class ). The enumerated type conforms to the general mode.Class Enum<E extends Enum<E>>, AndEThe name of the enumerated type. Each value of the enumeration type is mappedprotected Enum(String name, int ordinal)In the constructor, hereNameAre converted into oneStringAndOrdinal numberSetIndicatesThis settingOrder of creation.

The enum object declared in the code above actually calls the Enum (String name, int ordinal) constructor seven times. (Name is a constant, above is MON, TUE, etc., ordinal is the order of creation)

new Enum<EnumTest>("MON",0);new Enum<EnumTest>("TUE",1);new Enum<EnumTest>("WED",2);。。。。。。

 

2. switch

When we use switch, int and char are generally used, but enumeration can also be used in switch, and enumeration may be used to make our code more readable. The following is an example of enum enumeration.

Enum Color {GREEN, YELLOW, RED} public class TrafficLight {Color = color. RED; public void change () {switch (color) {case RED: System. out. println ("red"); break; case YELLOW: System. out. println ("yellow"); break; case GREEN: System. out. println ("green"); break ;}}}

3. Add a new method + traversal to Enumeration

When we use constants, we can have corresponding values when using interfaces. For example, the mon value of the IWeekConstants interface above is Mon, but enumeration does not seem to indicate this meaning. Next we will discuss the implementation of this method and the traversal of enumeration types.

The enumeration type provides constructor, which can be implemented by constructor and overwriting toString. The implementation code is as follows:

Package com. zcr. test; enum ActionTypeEnum {// assign values through parentheses and must contain a parameter constructor and an attribute and method. Otherwise, compilation errors may occur. // assign values to all parameters or do not assign values, some values cannot be assigned without assigning values. If values are not assigned, the constructor cannot be written, and the value assignment compilation also fails to download (1, "xiazai"), access (2, "fangwen "); int index; String name; private ActionTypeEnum (int index, String name) {this. index = index; this. name = name;} public int getIndex () {return index;} public void setIndex (int index) {this. index = index;} public String getName () {return name;} public void setName (String name) {this. name = name ;}} public class EnumTest {public static void main (String [] args) {ActionTypeEnum [] actionTypeEnums = ActionTypeEnum. values (); for (ActionTypeEnum actionTypeEnum: actionTypeEnums) {System. out. println ("name =" + actionTypeEnum. getName (); System. out. println ("index =" + actionTypeEnum. getIndex (); System. out. println ("oridary =" + actionTypeEnum. ordinal (); System. out. println ("this =" + actionTypeEnum); System. out. println ("Download value:" + actionTypeEnum. valueOf ("Download"); System. out. println ("name () method =" + actionTypeEnum. name (); System. out. println ("-------------- tell me the split line ------------------");}}}

Running result:

Name = xiazaiindex = 1 oridary = 0 this = download value: Download name () method = download -------------- let me split line ------------------ name = fangwenindex = 2 oridary = 1 this = access download value: download name () method = access -------------- ask me to split the line ------------------

4. Summary

We can regard enum as a common class, which can define some attributes and methods. The difference is that enum cannot use the extends keyword to inherit other classes, because enum has inherited java. lang. enum (java is a single inheritance), but can inherit interfaces.

  Thank you: Thank you for reading this 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.