Switch能否用string做参数
2017-11-23 20:51
127 查看
在Java5以前,switch(expr)中,exper只能是byte,short,char,int类型(或其包装类)的常量表达式。
从Java5开始,java中引入了枚举类型,即enum类型。
从Java7开始,exper还可以是String类型。
但是long在所有版本中都是不可以的。
jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。
hashcode返回的是int型
可以发现:进行switch的实际是hash值,然后用equals进行安全检查(因为hash值可能会发生碰撞),所以性能不如枚举。switch支持String其实是一个语法糖,在编译后的字节码文件中都会被还原成原生类型,并在相应位置插入了强制转换代码,底层的JVM在switch上并没有修改。
当传入switch的是null时,在运行时对一个null调用hashCode()方法,会抛出NullPointerException;如果case写的是null,那么在编译时无法求出hashcode,就会编译报错。
相关文章推荐
- Switch能否用string做参数?
- Switch能否用string做参数
- Java中 Switch能否用string做参数?
- Switch能否用string做参数?
- Switch能否用String做参数
- Switch能否用string做参数?
- Switch能否用string做参数?
- Switch能否用string做参数
- switch能否用String做参数?
- java中switch能否使用String作为参数?
- Switch能否用string做参数?
- Switch能否用string做参数
- Switch能否用string做参数
- Switch能否用string做参数?
- Switch能否用string做参数
- Switch能否使用String做参数
- Switch能否用String做参数?
- Switch能否用String做参数
- Switch能否用string做参数
- switch语句能否作用在byte上,能否作用在long上,能否作用在String上?——Java经典面试题系列