Java enum enumeration usage
1. Background:
Before JDK1.5, we define constants as follows: public static final String RED = "RED ";
When the enumeration type is added to JDK, We can group related constants into one enumeration class:
public enum Color {RED, GREEN, BLUE;}
This can be used as follows: Color c = Color. RED
Ii. Enumeration features:
1. enum enumeration is a special Java class that inherits from java. lang. Enum and inherits many Enum methods. However, an enumeration class is a final class that cannot be inherited.
2. Enumeration classes can be defined in interfaces or classes. Of course, the enumeration types include constructors, methods, and data fields:
public interface MyConstants {enum Color {RED("RED", 1), GREEN("GREEN", 2), BLUE("BLUE", 3);String desc;Integer value;private Color(String desc, Integer value) {this.desc = desc;this.value = value;}}enum Light {RED, GREEN, YELLOW;}}
Use: MyConstants. Color. RED
3. the constructor of an enumeration class is somewhat different from that of a common class:
(A) The constructor is called only when constructing enumeration values.
(B) The constructor can only be private. This ensures that external code cannot create new enumeration class instances.
4. All enumeration classes inherit the Enum method. The following describes how to use these methods:
(A). ordinal () returns the order in which the enumerated values are declared based on the enumerated values.
(B). compareTo () Enum implements the java. lang. Comparable interface. It returns the order difference between the two enumerated values, but these two enumerated values must belong to the same enumeration class.
(C). values returns an array containing all enumerated values.
(D). toString returns the name of the enumerated constant.
(E). valueOf similar toString
(F). equals compares the applications of two enumeration objects
5. Use the following in the switch:
public enum Light{RED, GREEN, YELLOW;}class Test {public static void main(String[] args) {Light light = Light.RED;switch (light) {case RED:System.out.println("it's red");break;case GREEN:System.out.println("it's green");break;case YELLOW:System.out.println("it's yellow");break;}}}