Switch能否用string做參數


在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


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM