能在 Switch 中使用 String 吗?

答:从 Java 7 开始,我们可以在 switch case 中使用字符串,但这仅仅是一个语法糖。内部实现在 switch 中使用字符串的 hashCode。

补充:

在JDK7以前,switch是不能够用String作为参数进行条件判断的,只能支持 byte、short、char、int或者其对应的封装类以及 enum 类型。但是在JDK之后,String作为参数是能够作为switch的参数,但是前提是你的jdk环境必须是JDK7以上的版本。 这里我们看一下代码(这里用的jdk环境为jdk1.7.0_79):

public class SwitchDemo {
          
   
    public static void main(String[] args) {
          
   
        String string = "Hello";
        switch (string) {
          
   
            case "Hello":
                System.out.println("Application is running on Hello mode");
                break;
            case "World":
                System.out.println("Application is running on World mode");
                break;
            case "Java":
                System.out.println("Application is running on Java mode");
                break;

            default:
                System.out.println("Application is running on default mode");
                break;
        }
    }
}

最后结果输出无疑为:Application is running on Hello mode,所以咋jdk1.7以上是能够以String作为Switch为参数的。但是值得思考的是,java中是真的支持了这一特性还是另有玄机呢,所以我们一起来看看生成的.class文件,我们利用反编译器来一探究竟:

import java.io.PrintStream;
public class SwitchDemo
{
          
   
    public SwitchDemo()
    {
          
   
    }
    public static void main(String args[])
    {
          
   
label0:
        {
          
   
            String string = "Hello";
            String s;
            switch ((s = string).hashCode())
            {
          
   
            default:
                break;

            case 2301506: 
                if (!s.equals("Java"))
                    break;
                System.out.println("Application is running on Java mode");
                break label0;

            case 69609650: 
                if (s.equals("Hello"))
                {
          
   
                    System.out.println("Application is running on Hello mode");
                    break label0;
                }
                break;

            case 83766130: 
                if (!s.equals("World"))
                    break;
                System.out.println("Application is running on World mode");
                break label0;
            }
            System.out.println("Application is running on default mode");
        }
    }
}

从上面反编译的代码中我们可以知道,jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。 最后可以得到结论:jdk1.7以后可以将String作为switch参数进行传递,其原理就是将字符串转换成hashCode值,然后在进行equals比较,也就是编译器在编译期间给代码做了转换。

经验分享 程序员 微信小程序 职场和发展