支持的类型有:char、byte、short、int、Character、Byte、Short、Integer、String、enum
与if区别:
- 分支较多时,用switch的效率很高,不管有多少case,都直接跳转,不需逐个比较查询
三个条件,if需要从上执行到下,对比三次,而switch由于采用的是Binary Tree算法,直接跳转,不需要逐个比较查询,这种方式类似于map的空间换时间;
- switch…case只能处理case为常量的情况,相对于if…else则灵活的多
- switch的效率与分支数无关。当只有分支比较少的时候,if效率比switch高(因为switch有跳转表)
- byte、char、short
byte、char、short 类型在编译期默认提升为 int,并使用 int 类型的字节码指令。所以对这些类型使用 switch,其实跟 int 类型是一样的。
- enum
enum最终也是转换为enum的int序号来适应switch的。
- string
switch 支持 String 其实就是语法糖。编译器会根据字符串的 hashCode 来处理。
String a = "aa";switch (a) {case "aa":System.out.println("111");break;case "AaAa":System.out.println("222");break;case "AaBB":System.out.println("333");break;}// 反编译后:String var1 = "aa";byte var3 = -1;switch(var1.hashCode()) { // 第一个switch,根据hashCode计算第二个switch内的位置case 3104:if (var1.equals("aa")) {var3 = 0;}break;case 2031744:if (var1.equals("AaBB")) {var3 = 2;} else if (var1.equals("AaAa")) {var3 = 1;}}switch(var3) { // 第二个switch,执行原switch的逻辑case 0:System.out.println("111");break;case 1:System.out.println("222");break;case 2:System.out.println("333");}// 先根据 hashCode 找出原始 switch 内的位置,再执行原代码逻辑
为什么不支持long类型?
原因就是 switch 对应的 JVM 字节码 lookupswitch、tableswitch 指令只支持 int 类型。
阿里巴巴开发规范中提到的问题
�
会报空指针
