How to use enum types in Java?
In Java, an enumeration type (Enum) is a special data type used to define a fixed set of values. Here is the basic syntax and usage of using Java enumeration types.
- Define an enumeration type:
enum Color {
RED, GREEN, BLUE
}
- Utilizing values of an enumeration type:
Color color = Color.RED;
- Compare the values of enumerated types:
if (color == Color.RED) {
// 执行代码
}
- Iterate through all values of an enumeration type:
for (Color c : Color.values()) {
System.out.println(c);
}
- Match the enum type values using a switch statement.
switch (color) {
case RED:
// 执行代码
break;
case GREEN:
// 执行代码
break;
case BLUE:
// 执行代码
break;
default:
// 执行代码
break;
}
- Add custom properties and methods to an enumeration type.
enum Color {
RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF");
private String code;
private Color(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
Color red = Color.RED;
System.out.println(red.getCode()); // 输出: #FF0000
In conclusion:
- Enumerated types can be used to define a set of constant values.
- Variables of enumeration type can only be assigned one value from the enumeration type.
- Values of enumeration types can be compared using comparison operators.
- The values of an enumerated type can be retrieved through the values() method for iteration.
- Enum values can be matched using a switch statement.
- Enumerated type can define custom properties and methods.