Although Java has an enumeration type of data type, but it is seldom used, in fact, when used in the week, month, Four seasons and other data sets, undoubtedly, the enumeration type is not only convenient to solve the problem of integer and string mapping, but also greatly improve the readability of the program.
The following is a simple program code to illustrate this problem:
1. Enumeration types are automatically assigned, and by default the enumeration variables are assigned to 0, 1, 2, 3, 4, 5, and so on, respectively. The name of the enumeration variable and its corresponding subscript are then printed in a circular fashion.
/ * * @author mnmlist * @date 8/18/2015 * @description of the basic usage of enum */ enum Color1 {red,gree N,blue,pink; Private Color1 () {}; public static void Printallvalues () {Color1 color:Color1.values ()) {System.out.println ("Name:" +color+ ", Index:" + Color.ordinal ());//Name and subscript} public static void Printonevalue () {System.out.println ("Name:" +red+ ", Index:" +red.ordinal ()); }}public class Enumdemo{public static void Main (string[] args) {//for (Color color:Color.values ())//color.printvalue (); System.out.println ("Print One Value:"); Color1.printonevalue (); System.out.println ("Print All Values:"); Color1.printallvalues ();}}
Results:
Print one Value:name:red,index:0print all Values:name:red,index:0name:green,index:1name:blue,index:2name:pink, Index:3
2. Use the constructor to assign the enumeration variable so that you can start with the value of a random integer instead of just 0
Enum color{red (3), YELLOW (5), BLUE (9);p rivate int value;private Color () {}private Color (int value) {this.value= Value;} public void Printvalue () {System.out.println ("Name:" +this.name () + ", Value:" +this.value);//name and corresponding value}}
public class Enumdemo{public static void Main (string[] args) {for (Color color:Color.values ()) Color.printvalue ();}}
Results:
Name:red,value:3name:yellow,value:5name:blue,value:9
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Use of enumeration types in Java