您的位置 首页 java

java基础:switch关键字支持String么?原理是什么?

在jdk1.7之前是不支持的, switch 中只支持int类型的。但是在之后支持了,是怎么做到的。这里面有个 语法糖 ,是将 String 换成了int类型。大致的意思是:

 public class switchDemoString {
    public  static   void  main(String[] args) {
        String str = "world";
        switch (str) {
        case "hello":
            System.out.println("hello");
            break;
        case "world":
            System.out.println("world");
            break;
        default:
            break;
        }
    }
}  

编译后如下所示:

 public class switchDemoString
{
    public switchDemoString()
    {
    }
    public static void main(String args[])
    {
        String str = "world";
        String s;
        switch((s = str).hashCode())
        {
        default:
            break;
        case 99162322:
            if(s.equals("hello"))
                System.out.println("hello");
            break;
        case 113318802:
            if(s.equals("world"))
                System.out.println("world");
            break;
        }
    }
}  

可以看到里面其实是使用了 hashCode 和equals。这两个方法之前是会在map和set中会使用,那么现在在这里也有个巧妙地使用了。按照这个思路,其实一个对象只要能够放到map中,就能够使用switch了。

文章来源:智云一二三科技

文章标题:java基础:switch关键字支持String么?原理是什么?

文章地址:https://www.zhihuclub.com/197357.shtml

关于作者: 智云科技

热门文章

网站地图