After enumerating classes have occurred from Jdk5, it is possible to define some dictionary values using enumeration types;
Enumeration is commonly used by values (): To iterate through the constant values in the enumeration;
valueof (string name): Gets the constant value defined in the enumeration class by name, and requires that the string be consistent with the enumeration's constant name;
The ToString () method is overridden in the enumeration class and returns the name of the enumeration constant;
In fact, ToString () and value are the opposite pair of operations. ValueOf is an enumeration constant object obtained by name. and ToString () is the name of the enumeration constant obtained by enumeration constants;
1 Packageenumtest;2 3 /**4 * Author:think5 * version:2018/7/16.6 */7 Public enumColor {8 9Red (0, "red"),TenBlue (1, "Blue"), OneGreen (2, "Greens"), A - ; - the //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. - Private intCode; - PrivateString desc; - +Color (intcode, String desc) { - This. Code =Code; + This. desc =desc; A } at - /** - * Define a static method by itself, return enumeration constant object by code - * @paramCode - * @return - */ in Public StaticColor GetValue (intcode) { - to for(Color color:values ()) { + if(Color.getcode () = =code) { - returncolor; the } * } $ return NULL;Panax Notoginseng - } the + A Public intGetCode () { the returnCode; + } - $ Public voidSetcode (intcode) { $ This. Code =Code; - } - the PublicString GetDesc () { - returndesc;Wuyi } the - Public voidSetdesc (String desc) { Wu This. desc =desc; - } About}
Test class
1 Packageenumtest;2 3 /**4 * Author:think5 * version:2018/7/16.6 */7 Public classEnumtest {8 Public Static voidMain (string[] args) {9 /**Ten * Values of the Test enumeration () One * A */ -String s = color.getvalue (0). GetDesc (); -System.out.println ("Gets the value:" +s); the - - - /** + * Test enumeration of valueof, the value inside can be the name of the enumeration constant that you define - * Where the valueof method converts the name of a string to an enumeration item, which is an enumeration that finds the literal value in an enumeration item and that parameter is equal. + */ A atColor Color =color.valueof ("GREEN"); - System.out.println (Color.getdesc ()); - - /** - * The ToString () method of the Test enumeration - */ in -Color s2 = color.getvalue (0) ; toSystem.out.println ("Gets the value:" +s2.tostring ()); + -}
Enumerates the ToString () valueof () and values () usages of an enum