Quoted and reproduced in: http://blog.csdn.net/ishallwin/article/details/9440251
1. What is an enumeration:
In actual programming, there are often such "datasets", whose values are stable in the program, and the elements in the "dataset" are limited.
For example: from Monday to Sunday , seven data elements formed the "data set" of the week, and four data elements formed the "datasets" of the Four seasons.
How do you better use these "datasets" in Java? So the enumeration comes in handy.
Enumerations are a means of limiting a limited number of possible values, and using enumerations can reduce the likelihood of program errors and improve the readability and maintainability of your code .
An enumeration in Java is not a collection of simple constants, but an object, which remains essentially a class,
So in addition to providing a range of related values, the enumeration in Java provides some additional functionality, even if you want to add it yourself.
2. General usage
Although the enumeration in Java is an object, most of the scenes that use it are not the same as in other languages.
2.1 Definitions
Defining enumerations requires the use of the keyword enum. For example, if an application needs to use a series of specific color values, you can define an enumeration that resembles the following form.
Here is a direct definition of a Mycolor.java file, the contents of the file are as follows:
1 // you do not need to write the class keyword here, because as long as there is an enum, the class automatically inherits 2 // Java.lang.Enum class 3 Public enum mycolor{4 // Each enumeration value is separated by commas, 5 RED,6 BLUE,7 GREEN; The last semicolon can be or not 8 }
View Code
You can see that the enum is really an object because the Mycolor.class file was generated:
2.2. Use
After the enumeration definition is complete, you can use the enumeration name . Enumeration to use the defined enumeration in code.
in special cases, if the program is able to identify the current enumeration type, you only need to give the enumerated item,
For example:
The constant value after the case keyword in the switch statement block.
1 Public classtest1{2 Public Static voidMain (string[] args) {3 //MyColor mycolor = new MyColor ();4 //it cannot be instantiated directly, although MyColor is essentially a class5 //it will be explained in detail later, because its construction method is private by default.6MyColor MyColor =mycolor.red;7 Switch(mycolor) {8 CaseBLUE://You can use the enumeration values directly here9System.out.println ("Blue");Ten Break; One CaseGREEN: ASystem.out.println ("Green"); - Break; - CaseRED: theSystem.out.println ("Red"); - Break; - default: -SYSTEM.OUT.PRINTLN ("What color?") "); + Break; - } + } A}View Code3. Common methods for enum types
The Java enumeration provides several methods for developers to invoke when needed.
For enumeration objects, the primary available method is values (), which returns a collection of all the enumerated items defined in the current enumeration;
For enumeration entries, the main methods available are 3 methods ordinal (),name (), and getdeclaringclass ().
Method ordinal () returns the ordinal of an enumerated item in an enumeration object, starting at 0;
The method name () returns the name of the enumeration item (same as the method ToString effect), and is typically used to obtain the name of an enumerated item saved in an enumeration variable;
Method Getdeclaringclass () is used to obtain the full name of the class where the current enumeration value resides.
In addition, enumeration items can also be compared by method CompareTo () , which returns 0 if the parameter passed in an enumerated item equal to the current value.
Test code:
Packagenet.yanzhijun.example;
Enummycolor
{
RED,
BLUE,
GREEN;
}
Publicclass Enumexample
{
public static void Main (string[] args)
{
MyColor color0 = mycolor.red;
Switch (COLOR0)
{
Case RED:
System.out.println ("Red");
Break
Case BLUE:
System.out.println ("Blue");
Break
Case GREEN:
System.out.println ("green");
Break
Default
SYSTEM.OUT.PRINTLN ("Unknown Color");
Break
}
For (MyColor myColor:MyColor.values ())
{
System.out.println (MyColor);
System.out.println (Mycolor.ordinal ());
System.out.println (Mycolor.name ());
System.out.println (Mycolor.getdeclaringclass ());
System.out.println ("============================================");
}
MyColor Color1 = mycolor.valueof ("RED");
System.out.println (Color1);
System.out.println (Color1.ordinal ());
System.out.println (Color1.name ());
System.out.println (Color1.getdeclaringclass ());
}
}
Its running result 1:
Figure 1
Ii. adding constructors and member methods for enumerations
1. Constructors
Class has constructors, enumerations are special classes, so enumerations can also have their own constructors. However, unlike a normal class, the constructor of an enumeration cannot be public, because the constructor is used when it is constructed for an enumeration item in an enumeration object, and it does not need to be used outside of the enumeration object.
For example, if you want each enumeration item in the enumeration MyColor to contain a corresponding Chinese description and its corresponding color information, you can add a constructor for MyColor that contains two arguments, and use this constructor to construct each enumerated item when it is declared. The implementation code is as follows:
Enum MyColor
{
Red ("Color.Red"),
Blue ("Blues", Color.Blue),
Green ("Color.green");
Private String Summy;
private color color;
Private MyColor (stringsummy, color color)
{
This.summy = Summy;
This.color = color;
}
}
2. Member Methods
You can add a method to an enumeration just as you can add a constructor for an enumeration. For example, in the code above, a Chinese description and its corresponding color information are added to each enumeration item through the constructor, so in order to take out the information corresponding to the enumeration, you need to add the following method for the enumeration MyColor.
Public String Getsummy ()
{
return this.summy;
}
Public Color GetColor ()
{
return this.color;
}
It can be seen that through the above mechanism, the meaning of the enumeration itself can be well integrated with its specific information, eliminating the drawbacks of the meaning and information separation in the traditional programming language.
The enumeration constructor, the member aspect, and the complete test code are as follows:
Packagenet.yanzhijun.example;
Importjava.awt.Color;
Enummycolor
{
Red ("Color.Red"),
Blue ("Blues", Color.Blue),
Green ("Color.green");
Private String Summy;
private color color;
Private MyColor (String summy, color color)
{
This.summy = Summy;
This.color = color;
}
Public String Getsummy ()
{
return this.summy;
}
Public Color GetColor ()
{
return this.color;
}
}
Publicclass EnumExample2
{
public static void Main (string[] args)
{
For (MyColor myColor:MyColor.values ())
{
System.out.println (MyColor);
System.out.println (Mycolor.getsummy ());
System.out.println (Mycolor.getcolor ());
System.out.println ("==============================");
}
MyColor color1 =mycolor.valueof ("RED");
System.out.println (Color1);
System.out.println (Color1.getsummy ());
System.out.println (Color1.getcolor ());
}
}
It runs as shown in result 2.
Figure 2
Iii. Enumeration Collection
An enumeration in Java is an object, and each enumeration item in an enumeration object is also an object. In Java, a collection container requires that every member stored therein is an object type, and enumerations are a special class, and Java also provides collections containers Enumset and enummap for enumerations.
1. Enumset
The enumset is used to hold the collection of enumerated items, which is particularly useful in cases where the enumeration items themselves are not mutually exclusive. For example, an application system typically has multiple roles, and some people may assume more than one role in the system. If these roles are defined through enumerations, then Enumset will be able to save multiple roles together to identify all roles that a particular user assumes.
Enumset is extended to Abstractset, which, in addition to the methods owned by the normal set, mainly adds a series of methods to generate Enumset instances (noneof, AllOf, CopyOf, Complementof, of, range, etc.).
The following is an example of using the enumset of method to produce an Enumset instance.
Package net.yanzhijun.example;
Import Java.util.EnumSet;
Enum Role
{
Sysadmin
Rolea,
Rolec;
}
public class Enumsetexample
{
public static Voidmain (string[] args)
{
Enumset<role> es= enumset.of (Role.rolea, Role.roleb);
for (Role role:es)
{
SYSTEM.OUT.PRINTLN (role);
}
}
}
2. Enummap
Enummap is a map that must use an enumeration entry as its key, similar to the normal map. The following routines place the Chinese meanings of the two types of roles into a Enummap object, and then call the size and get methods of the Enummap.
Packagenet.yanzhijun.example;
Importjava.util.EnumMap;
Enum Role
{
Sysadmin
Rolea,
Roleb,
Rolec;
}
Publicclass Enummapexample
{
public static void Main (string[] args)
{
Enummap<role, string> em = Newenummap<role, string> (Role.class);
Em.put (role.sysadmin, "system Administrator");
Em.put (Role.rolea, "role a");
System.out.println (Em.size ());
System.out.println (Em.get (role.sysadmin));
}
}
Enumeration types for Java