2.Switch语句的参数类型

Switch语句的参数类型

JDK1.6 的版本中,switch后面的括号里面只能放int类型的值,注意是只能放int类型,但是放byte,short,char类型的也可以。是因为byte,short,shar可以自动提升(自动类型转换)为int。而不能放long型和String型。

JDK1.7 的版本中,switch中可以使用字串String。但仍不支持long型。

原理:hashCode()+equals() 
编译器在编译期间给代码做了转换。

原始代码:

public class StringInSwitchCase { 
      public static void main(String[] args) { 
            String mode = args[0]; 
            switch (mode) { 
                  case "ACTIVE": 
                        System.out.println("Application is running on Active mode"); 
                        break; 
                  case "PASSIVE":
                        System.out.println("Application is running on Passive mode"); 
                         break; 
                  case "SAFE": 
                          System.out.println("Application is running on Safe mode"); 
          } 
      } 
}

 

编译器优化后:

import java.io.PrintStream; 

public class StringInSwitchCase{ 
      public StringInSwitchCase() { } 

      public static void main(string args[]) { 
             String mode = args[0]; 
            String s; switch ((s = mode).hashCode()) { 
                  default: break; 
                  case -74056953: 
                        if (s.equals("PASSIVE")) { 
                                    System.out.println("Application is running on Passive mode"); 
                         } 
                        break; 
                  case 2537357: 
                        if (s.equals("SAFE")) { 
                              System.out.println("Application is running on Safe mode"); 
                         } 
                        break; 
                  case 1925346054: 
                        if (s.equals("ACTIVE")) { 
                              System.out.println("Application is running on Active mode"); 
                         } 
                        break; 
               } 
          } 
}

转载于:https://my.oschina.net/u/997707/blog/804765

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值