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.

  1. Define an enumeration type:
enum Color {
  RED, GREEN, BLUE
}
  1. Utilizing values of an enumeration type:
Color color = Color.RED;
  1. Compare the values of enumerated types:
if (color == Color.RED) {
  // 执行代码
}
  1. Iterate through all values of an enumeration type:
for (Color c : Color.values()) {
  System.out.println(c);
}
  1. Match the enum type values using a switch statement.
switch (color) {
  case RED:
    // 执行代码
    break;
  case GREEN:
    // 执行代码
    break;
  case BLUE:
    // 执行代码
    break;
  default:
    // 执行代码
    break;
}
  1. 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:

  1. Enumerated types can be used to define a set of constant values.
  2. Variables of enumeration type can only be assigned one value from the enumeration type.
  3. Values of enumeration types can be compared using comparison operators.
  4. The values of an enumerated type can be retrieved through the values() method for iteration.
  5. Enum values can be matched using a switch statement.
  6. Enumerated type can define custom properties and methods.
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds