在case語句中不要使用枚舉類型來引用,直接使用枚舉類型的常量名稱便可。this
在閱讀Java書籍和官方文檔的時候,都說Java的Switch語句是支持枚舉的,可是在網上找相關實例的時候卻沒有找到。經過查看官方文檔,明白了使用方法。
枚舉是一種static final的常量,可是在switch使用時和平時引用靜態常量有區別。由於switch條件中的枚舉類型必須和case語句裏面的一致,因此當在switch語句中聲明瞭枚舉類型以後,case語句就已經肯定了枚舉類型,因此不須要在使用枚舉類來引用了。spa
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
複製代碼
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY://switch條件語句已經肯定了枚舉類型,不須要再使用枚舉類型來引用枚舉常量,不然編譯出錯
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY: case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}複製代碼