天天看點

switch語句在JDK1.7前後所接受的類型

switch語句:

JDK1.0-1.4 資料類型接受 byte short int char

JDK1.5       資料類型接受 byte short int char enum(枚舉)

JDK1.7       資料類型接受 byte short int char enum(枚舉),String 六種類型

詳情請見:​​java switch語句與switch接受的資料類型​​

當switch語句使用了String類型進行判斷,出現錯誤(Cannot switch on a value of type String for source level below 1.7. Only con)

更改jdk版本為1.7以上即可解決

switch語句在JDK1.7前後所接受的類型

對于編譯器來說,​

​switch​

​中其實隻能使用整型,任何類型的比較都要轉換成整型

通過看H神的部落格才了解switch中String是文法糖,把位元組碼檔案反編譯後,确實是先将字元串轉換為哈希值,在去比對,之後再進行equals()方法進行字元串内容的比較.

通過例子來深入了解吧.

package top.clearlight.blog.sugar;

public class StringSwitchSuger {
    public static void main(String[] args) {

        String str = "yellow";

        switch (str) {
            case "red":
                System.out.println("The color is red");
                break;
            case "yellow":
                System.out.println("The color is yellow");
                break;
            case "black":
                System.out.println("The color is black");
                break;
            default:
                System.out.println("Input error");
                break;
        }

        char ch = 'a';

        switch (ch) {
            case 'a':
                System.out.println("a");
                break;
            default:
                System.out.println("預設");
                break;
        }

    }
}      

反編譯後的代碼 :

import java.io.PrintStream;

public class StringSwitchSuger
{

  public StringSwitchSuger()
  {
  }

  public static void main(String args[])
  {
    String str = "yellow";
    String s = str;
    byte byte0 = -1;
    switch (s.hashCode())
    {
    case 112785: 
      if (s.equals("red"))
        byte0 = 0;
      break;

    case -734239628: 
      if (s.equals("yellow"))
        byte0 = 1;
      break;

    case 93818879: 
      if (s.equals("black"))
        byte0 = 2;
      break;
    }
    switch (byte0)
    {
    case 0: // '\0'
      System.out.println("The color is red");
      break;

    case 1: // '\001'
      System.out.println("The color is yellow");
      break;

    case 2: // '\002'
      System.out.println("The color is black");
      break;

    default:
      System.out.println("Input error");
      break;
    }
    char ch = 'a';
    switch (ch)
    {
    case 97: // 'a'
      System.out.println("a");
      break;

    default:
      System.out.println("預設");
      break;
    }
  }
}      

對于上面的幾個數,其實就是幾個字元串的哈希值.