許裕永 譯 (原文內容取自 Oracle 官網)
Strings in switch Statements - You can use the String class in the expression of a switch statement.Strings 在 switch 敍述中 - 你可以在 switch 敍述中使用 String 類別.
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
switch 敍述在與其相關的每一個 case 標籤進行比對 String 物件的運算時, 就如同使用 String.equals 方法; 所以在 switch 敍述中對於 String 物件的比對是有區分大小寫的. 使用 switch 敍述比對 String 物件, Java 編譯器通常會產生比使用 if-then-else 鏈結敍述比對 String 物件更加有效率的 bytecode.
沒有留言:
張貼留言