switch如何对String和枚举类的支持呢?
下文笔者讲述讲述switch对String和枚举类的支持简介说明,如下所示
我们都知道switch关键字只能支持整数类型 但是switch后可支持String类型, 则编译器会将String转换为hashCode值 然后再进行switch选择 --------------------------------------------------- 如果switch后面跟Enum类型 则转换为枚举类型的下标(ordinal)例:
public class SwitchTest {
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 723243535
//这边需要再次通过equals方法进行判断,因为不同字符串的hashCode值是可能相同的,比如“Aa”和“BB”的hashCode就是一样的
if(s.equals("hello"))
System.out.println("hello");
break;
case 12324242:
if(s.equals("world"))
System.out.println("world");
break;
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


