Use Java enumerations instead of strings or static variables.
-1. Simple to use
Color Enumeration classes:
public enum Colorenum {
RED, BLACK, GREE, BLUE
}
Call:
public static void Main (string[] args) {
System.out.println (ColorEnum.RED.toString ());
System.out.println (ColorEnum.RED.ordinal ());
}
-2. Custom enumeration values
public enum Colorenum {
RED (1), BLACK (2), GREE (3), BLUE (4);
Private final intvalue;
public int GetValue () {
return value;
}
Colorenum (int value) {
This.value =value;
}
}
System.out.println (ColorEnum.RED.getValue ());
-3. Traverse-Cycle
For (Colorenum item:ColorEnum.values ()) {
System.out.println (Item.getvalue () + ":" + item.tostring ());
}
-4. Type conversion-Converts a string to an enumeration
Stringvalue1= "BLUE";
System.out.println (Colorenum.valueof (value1). ordinal ());
-To convert a number to an enumeration, because it is an array, you need to follow your own starting value
int value2 = 2;
System.out.println (Colorenum.values () [Value2-1].tostring ());
-5. Judging-Switch judgment-First, the number or string is converted to an enumeration to determine
Colorenum value3 = Colorenum.values () [value2-1];
Switch (VALUE3) {
Case RED:
System.out.println (ColorEnum.RED.getValue () + ":" + ColorEnum.RED.toString ());
Break
Case BLACK:
System.out.println (ColorEnum.BLACK.getValue () + ":" + ColorEnum.BLACK.toString ());
Break
Case GREE:
System.out.println (ColorEnum.GREE.getValue () + ":" + ColorEnum.GREE.toString ());
Break
Default
System.out.println (ColorEnum.BLUE.getValue () + ":" + ColorEnum.BLUE.toString ());
}
You can also continue to extend the use of enumerations.
Experience Summary 53--java Enumeration