The role and benefits of Java enumeration

Source: Internet
Author: User

An enumeration is a specification that regulates the form of parameters, so that it is not possible to consider the type mismatch and explicitly replace the fuzzy concept enumerated by the int parameter as a class and an array.

As a new keyword introduced by Sun, Enum looks like a special class, it can also have its own variable, can define its own method, can implement one or more interfaces. When we declare an enum type, we should be aware of some of the characteristics of the enum type.

1. It cannot have a public constructor, which ensures that the client code has no way to create an instance of the enum.

2. All enumerated values are public, static, final. Note that this is only for enumeration values, and we can define any other type of non-enumeration variable as you would define a variable in a normal class, which can use any modifier you want to use.

3. Enum implements the Java.lang.Comparable interface by default.

4. The enum contains the ToString method, so if we call Color.Blue.toString (), the string "Blue" is returned by default.

5. Enum provides a valueof method that corresponds to the ToString method. Calling valueof ("Blue") will return Color.Blue. So we have to be aware of this when we rewrite the ToString method, which should be a relative rewrite of the valueof method.

6. Enum also provides the values method, which allows you to easily iterate through all of the enumeration values.

7. Enum also has a oridinal method that returns the order of enumeration values in the enumeration class, which depends on the order in which the enumeration values are declared, where Color.Red.ordinal () returns 0.

With these basic features in view, let's take a look at how to use them.

1. Iterates through all the enumerated values. Knowing the values method, we can pro with the Foreach Loop to iterate over the enumeration values.

For (Color c:color.values ())
System.out.println ("Find value:" + C);

2. Define methods and variables in the enum, such as we can add a method to color to randomly return a colour.

public enum Color {
Red,
Green,
Blue;


private static int number = Color.values (). length;


public static Color Getrandomcolor () {
Long random = System.currenttimemillis ()% number;
switch ((int) random) {
Case 0:
return color.red;
Case 1:
return color.green;
Case 2:
return color.blue;
Default:return color.red;
}
}
}

It can be seen that there is no difference between defining variables and methods in an enumeration type and defining methods and variables within a normal class. The only thing to note is that the variables and method definitions must be placed after all the enumeration value definitions, or the compiler will give an error.

3. Load (override) ToString, valueof method

We already know that Enum provides methods such as tostring,valueof, and many times we need to override the default ToString method, so what do we do with enums? In fact, this is no different from the ToString method of loading a normal class.

....
Public String toString () {
Switch (this) {
Case Red:
return "Color.Red";
Case Green:
return "Color.green";
Case Blue:
return "Color.Blue";
Default
Return "Unknow Color";
}
}
....

At this point we can see that the previous traversal code is then printed out

Color.Red
Color.green
Color.Blue

Instead of

Red
Green
Blue.

You can see that ToString is actually covered. In general, we should also review the valueof method in order to maintain their mutual consistency when we load the ToString.

4. Using constructors

Although enum can not have a public constructor, we can still define the private constructor, which is used inside the enum. Or the example of color.

public enum Color {
Red ("This is Red"),
Green ("This is Green"),
Blue ("This is Blue");

Private String desc;

Color (String desc) {
THIS.DESC = desc;
}

Public String GetDesc () {
return THIS.DESC;
}

}

Here we provide a descriptive message for each color, and then define a constructor to accept the description information.

Note that the constructor cannot be public or protected, so that the constructor can only be used internally, and the client code cannot new an instance of the enumeration value. This is perfectly reasonable, because we know that the enumeration value is a constant of public static final.

5. Implementing a specific interface

We already know that an enum can define variables and methods, and that it implements an interface as well as an interface to an ordinary class, and this is not an example.

6. Defines the method that enumerates the values themselves.

Before we see that we can define some methods for enum, we can even define a method for each enumeration value. Thus, the example of the ToString that we have previously covered can be rewritten as such.

public enum Color {
Red {
Public String toString () {
return "Color.Red";
}
},
Green {
Public String toString () {
return "Color.green";
}
},
blue{
Public String toString () {
return "Color.Blue";
}
};
}

Logically this is clearer than providing a "global" ToString method.

In general, Enum, as a completely new type of definition, is a much simpler and easier-to-understand code to help programmers write

People feel that there is generally no need to use too many of the advanced features of enum, otherwise it is easy to understand the original intention to violate the

The role and benefits of Java enumeration

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.