在Java中,使用enum類型和switch語句可以更加清晰地表示一組常量值。下面是一些使用enum和switch的技巧:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
// 其他case語句...
}
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;
switch (day) {
case MONDAY:
System.out.println("Today is " + day.getDisplayName());
break;
// 其他case語句...
}
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday");
break;
default:
System.out.println("Today is not Monday");
}
總的來說,使用enum和switch可以簡化代碼,使代碼更加清晰和易于維護。當有一組相關的常量值需要處理時,推薦使用enum和switch來實現。