溫馨提示×

java枚舉使用的方法是什么

小億
82
2024-05-24 09:10:13
欄目: 編程語言

在Java中,枚舉類型使用enum關(guān)鍵字來定義。枚舉類型可以包含常量、方法和構(gòu)造函數(shù)。以下是枚舉類型的一些使用方法:

  1. 定義枚舉類型:
public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
  1. 訪問枚舉常量:
Day day = Day.MONDAY;
System.out.println(day); // 輸出 MONDAY
  1. 使用枚舉類型中的方法:
public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    
    public boolean isWeekend() {
        return this == SATURDAY || this == SUNDAY;
    }
}

Day day = Day.SATURDAY;
System.out.println(day.isWeekend()); // 輸出 true
  1. 使用values()方法獲取枚舉常量數(shù)組:
Day[] days = Day.values();
for (Day day : days) {
    System.out.println(day);
}
  1. 使用valueOf()方法根據(jù)字符串獲取枚舉常量:
Day day = Day.valueOf("MONDAY");
System.out.println(day); // 輸出 MONDAY
  1. 實現(xiàn)枚舉類型的構(gòu)造函數(shù)和方法:
public enum Day {
    MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
    
    private String displayName;
    
    Day(String displayName) {
        this.displayName = displayName;
    }
    
    public String getDisplayName() {
        return displayName;
    }
}

Day day = Day.MONDAY;
System.out.println(day.getDisplayName()); // 輸出 Monday

0