Switch可否用string作參數

在jdk 7 以前,switch 只能支持 byte、short、char、int 這幾個基本數據類型和其對應的封裝類型。switch後面的括號裏面只能放int類型的值,但因爲byte,short,char類型,它們會 自動 轉換爲int類型(精精度小的向大的轉化),因此它們也支持。express

注意,對於精度比int大的類型,好比long、float,doulble,不會自動轉換爲int,若是想使用,就必須強轉爲int,如(int)float;spa

jdk1.7以前,爲何不能夠呢?code

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,字符串均可以。blog

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從而進行判斷。string

具體能夠參考:http://freish.iteye.com/blog/1152921hash

相關文章
相關標籤/搜索