在jdk 7 之前,switch 只能支持 byte、short、char、int 這幾個基本數據類型和其對應的封裝類型。switch后面的括號里面只能放int類型的值,但由於byte,short,char類型,它們會 自動 轉換為int類型(精精度小的向大的轉化),所以它們也支持。
注意,對於精度比int大的類型,比如long、float,doulble,不會自動轉換為int,如果想使用,就必須強轉為int,如(int)float;
jdk1.7之前,為什么不可以呢?
switch (expression) // 括號里是一個表達式,結果是個整數 { case constant1: // case 后面的標號,也是個整數 group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements }
jdk1.7后,整形,枚舉類型,boolean,字符串都可以。
public class TestString { static String string = "123"; public static void main(String[] args) { switch (string) { case "123": System.out.println("123"); break; case "abc": System.out.println("abc"); break; default: System.out.println("defauls"); break; } } }
為什么jdk1.7后又可以用string類型作為switch參數呢?
其實,jdk1.7並沒有新的指令來處理switch string,而是通過調用switch中string.hashCode,將string轉換為int從而進行判斷。
具體可以參考:http://freish.iteye.com/blog/1152921