天天看点

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;
    }
  }
}      

对于上面的几个数,其实就是几个字符串的哈希值.