Switch能否用string做参数
2017-04-14 22:24
190 查看
在jdk7之前,switch只能支持byte、short、char、int这几个基本数据类型和其对应的封装类型。switch后面的括号里面只能放int类型的值,但由于byte,short,char类型,它们会自动转换为int类型(精精度小的向大的转化),所以它们也支持。注意,对于精度比int大的类型,比如long、float,doulble,不会自动转换为int,如果想使用,就必须强转为int,如(int)float;jdk1.7之前,为什么不可以呢?
switch(expression)//括号里是一个表达式,结果是个整数 { caseconstant1://case后面的标号,也是个整数 groupofstatements1; break; caseconstant2: groupofstatements2; break; . . . default: defaultgroupofstatements }jdk1.7后,整形,枚举类型,boolean,字符串都可以。
publicclassTestString{ staticStringstring="123"; publicstaticvoidmain(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并没有新的指令来处理switchstring,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。具体可以参考:http://freish.iteye.com/blog/1152921
相关文章推荐
- 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做参数?
- Java中 Switch能否用string做参数?
- Switch能否用String做参数
- Switch能否用string做参数
- switch语句能否作用在byte上,能否作用在long上,能否作用在String上?