Switch能否用string做参数
2018-02-08 09:02
260 查看
在jdk 7 之前,switch 只能支持 byte、short、char、int 这几个基本数据类型和其对应的封装类型。switch后面的括号里面只能放int类型的值,但由于byte,short,char类型,它们会 自动 转换为int类型(精精度小的向大的转化),所以它们也支持。
注意,对于精度比int大的类型,比如long、float,doulble,不会自动转换为int,如果想使用,就必须强转为int,如(int)float;
jdk1.7之前,为什么不可以呢?switch (expression) // 括号里是一个表达式,结果是个整数
{
case constant1: // case 后面的标号,也是个整数
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
jdk1.7后,整形,枚举类型,boolean,字符串都可以。
其实,jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。
具体可以参考:http://freish.iteye.com/blog/1152921
注意,对于精度比int大的类型,比如long、float,doulble,不会自动转换为int,如果想使用,就必须强转为int,如(int)float;
jdk1.7之前,为什么不可以呢?switch (expression) // 括号里是一个表达式,结果是个整数
{
case constant1: // case 后面的标号,也是个整数
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
default group of statements
}
jdk1.7后,整形,枚举类型,boolean,字符串都可以。
public class TestString { static String string = "123"; public static void main(String[] args) { switch (string) { case "123": System.out.println("123"); break; case "abc": System.out.println("abc"); break; default: System.out.println("defauls"); break; } } }为什么jdk1.7后又可以用string类型作为switch参数呢?
其实,jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。
具体可以参考:http://freish.iteye.com/blog/1152921
相关文章推荐
- Switch能否用string做参数
- Switch能否用string做参数?
- Switch能否用string做参数?
- java中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能否用string做参数?
- Switch能否用string做参数
- switch语句能否作用在byte上,能否作用在long上,能否作用在String上?