博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2.Switch语句的参数类型
阅读量:7033 次
发布时间:2019-06-28

本文共 1874 字,大约阅读时间需要 6 分钟。

hot3.png

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

你可能感兴趣的文章
下载编译webrtc for ios
查看>>
localhost与127.0.0.1区别
查看>>
Python异常处理
查看>>
对某图书馆***一次笔记
查看>>
redis介绍以及安装
查看>>
subversion 权威指南 1.4
查看>>
转:[web]javascript 增加表單的input
查看>>
FHS
查看>>
apache 配置多个本地路径
查看>>
signal
查看>>
matlab 7.0安装后运行jvm.dll错误
查看>>
mysql主从复制碰到的小问题
查看>>
编写一个UNIX文件系统
查看>>
textView跳转的activity
查看>>
PHP版本VC6和VC9、Non Thread Safe和Thread Safe的区别
查看>>
我的友情链接
查看>>
fix [Errno 13] Permission denied: '/var/log/glance/api.log'
查看>>
Cacti 0.8.8b 插件(monitor thold setting realtime)安装及邮件 短信告警
查看>>
我的友情链接
查看>>
很好的一个文字工具网址
查看>>