The enum keyword is a seemingly small feature. With this keyword, we can create an enumeration type.
In fact, when you use the enum keyword to create a new Enumeration type, you actually create a subclass of the java. lang. Enum class. Each specified value in enumeration can be considered as an instance of this class.
However, we don't need to care about the nature of enumeration. We just need to use it as a way to create a data type, and then we can use the obtained type directly.
Some constants are often used during project development, such as a set of possible values of an attribute. We do not recommend that you directly judge the constant value in the Program (this is prone to errors and requires developers to remember the exact value of each constant ). You can use the enumeration type to save a set of unchanged values.
[Java]
Public enum State {
ACTIVE, CLOSED
}
Enumeration also has a very practical feature, that is, it is applied in the switch statement. This greatly improves the readability of the program.
[Java]
State currentState = State. ACTIVE;
Switch (currentState ){
Case ACTIVE:
// Blabla
Break;
Case CLOSED:
// Blabla
Break;
}
We can add various variables and methods in the enumeration class, or overwrite a method (such as toString ()).
[Java]
Public enum State {
ACTIVE ("Active", 1), CLOSED ("Closed", 0 );
// Member variables, constructor, get/set method, override method, etc.
}
The EnumMap and EnumSet classes allow us to process enumeration types more conveniently.
The EnumMap class is a special implementation of the java. util. Map interface. The key in this interface is an enumeration type.
[Java]
Map <State, Integer> map = new EnumMap <State, Integer> (State. class );
Map. put (State. ACTIVE, 1 );
The EnumSet class implements the java. util. Set interface, which saves a Set of enumerated values. We can use it to save a Set of features/attribute values. EnumSet allows us to operate on a group of enumerations like other Set objects.