码迷,mamicode.com
首页 > 其他好文 > 详细

Switch能否用string做参数

时间:2017-04-15 00:31:10      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:const   system   express   string转换   long   string   .com   ring   数据   

在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,字符串都可以。

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做参数

标签:const   system   express   string转换   long   string   .com   ring   数据   

原文地址:http://www.cnblogs.com/lchzls/p/6711222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!