switch

在Java7之前,switch只能支持 byte、short、char、int或者其对应的封装类以及Enum类型。在Java7中,加入了对String支持。

 1、int型

int i = 3;
        switch (i) {
        case 1:
            System.out.println(1);
            break;
        case 2:
            System.out.println(2);
            break;
        default:
            System.out.println(0);
        }

输出:0

2、enum类型

public enum Size {
    S, M, L
};
switch (Size.M) {
        case S:
            System.out.println("小");
            break;
        case M:
            System.out.println("中 ");
            break;
        default:
            System.out.println("无");
        }

输出:中

3、String

String s = "M";
        switch (s) {
        case "S":
            System.out.println("小");
            break;
        case "M":
            System.out.println("中 ");
            break;
        default:
            System.out.println("无");
        }

输出:中

分析(String类型)

package jichu;

public class TestSwitch {
    public void test(String s) {
        switch (s) {
        case "S":
            System.out.println("小");
            break;
        case "M":
            System.out.println("中 ");
            break;
        default:
            System.out.println("无");
        }
    }
}

字节码反编译后:

package jichu;

import java.io.PrintStream;

public class TestSwitch
{
  public void test(String s)
  {
    String str;
    switch ((str = s).hashCode())
    {
    case 77: 
      if (str.equals("M")) {
        break;
      }
    case 83: 
      if ((goto 78) && (str.equals("S")))
      {
        System.out.println("小");
        return;
        
        System.out.println("中 ");
      }
      break;
    }
    System.out.println("无");
  }
}

从中可以看出:

1、通过hashCode()求出字符串的hashCode,因为需要调用hashCode(),所以传入的String值不能为空,否则报空指针异常。

2、通过equals方法比较输入值。


为什么switch支持byte,short,char,String,而不支持long类型?

java7之前,在switch(expr)中,expr只能是一个整数表达式或者枚举常量,整数表达式可以是int基本类型或Integer包装类型;

由于,byte,short,char都可以隐含转换为int,所以,这些类型以及这些类型的包装类型也是可以的。

java7之后,加入了对String的支持。

long类型不符合switch的语法规定,并且不能被隐式转换成int类型,所以,它们不能作用于swtich语句中。

posted @ 2016-11-18 16:22  SQP51312  阅读(288)  评论(0编辑  收藏  举报