在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了。