在 Java SE 7 中,可以在 switch
述句中使用 String
物件:
// Before
Mode mode = null;
String day = getDay();
if ("Monday".equals(day) || "Wednesday".equals(day)) {
mode = MODE.TEA_TIME;
} else if ("Friday".equals(day)) {
mode = MODE.BEER;
} else if ("Saturday".equals(day) || "Sunday".equals(day)) {
mode = MODE.SLEEP;
} else {
mode = MODE.WORK;
}
// After
Mode mode = null;
String day = getDay();
switch (day) {
case "Monday":
case "Wednesday": mode = MODE.TEA_TIME; break;
case "Friday": mode = MODE.BEER; break;
case "Saturday":
case "Sunday": mode = MODE.SLEEP; break;
default: mode = MODE.WORK;
}
switch
述句會使用 String.equals
方法來比較每一個 case
標籤的字串物件,因此在 switch
述句中的字串比對是有大小寫分別的。
// Truth in JVM
Mode mode = null;
String day = getDay();
byte byte0 = -1;
switch(day.hashcode()) {
case -1984635600:
if (day.equals("Monday")) {
byte0 = 0;
}
break;
case -897468618:
if (day.equals("Wednesday")) {
byte0 = 1;
}
break;
case 2112549247:
if (day.equals("Friday")) {
byte0 = 2;
}
break;
// Others...
}
switch(byte0) {
case 0:
case 1: mode = MODE.TEA_TIME; break;
case 2: mode = MODE.BEER; break;
// Others...
}
和一連串的 if-then-else
相比,在 switch
述句中使用字串會更有效率,並且容易閱讀。