Switch用String做参数
来源:互联网 发布:淘宝店铺行业怎么改 编辑:程序博客网 时间:2024/05/20 18:47
Switch能否用String做参数?
参数可以是整数表达式,JDK1.5开始支持Enum类,JDK1.7开始支持String。
当字符串不会频繁改变时可以用枚举来代替String:用Enum.parse。
public enum Weekend { Monday, Tuesday, Friday, } public void Test(string week) { Weekend weekend = (Weekend)Enum.Parse(typeof(Enum), week, false);//转换一下 switch (weekend) { case Weekend.Monday: Console.WriteLine("Today is Monday"); break; case Weekend.Tuesday: Console.WriteLine("Today is Tuesday"); break; case Weekend.Friday: Console.WriteLine("Today is Friday"); break; default: break; } }
注意:
1.整数表达式可以是int和Integer,而byte、short、char等可以转换成int,所以也可以用。但是long和String不能转换成int,所以不能用
2.String时不能传入null作为参数,同时case语句中使用的字符串也不能为null,因为底层是通过equals和hashmap来判断的
</pre><pre name="code" class="javascript">public class Test { public void test(String str) { switch(str) { case "abc": System.out.println("abc"); break; case "def": System.out.println("def"); break; default: System.out.println("default"); } }}
反编译后的结果:
public class Test { public void test(String str) { int i = -1; switch(str.hashCode()) { case 96354: // "abc".hashCode() if (str.equals("abc")) { i = 0; } break; case 99333: // "def".hashCode() if (str.equals("def")) { i = 1; } break; default: break; } switch(i) { case 0: System.out.println("abc"); break; case 1: System.out.println("def"); break; default: System.out.println("default"); } }}PS:hashcode返回的是int型
可以发现:进行switch的实际是hash值,然后用equals进行安全检查(因为hash值可能会发生碰撞),所以性能不如枚举。switch支持String其实是一个语法糖,在编译后的字节码文件中都会被还原成原生类型,并在相应位置插入了强制转换代码,底层的JVM在switch上并没有修改。
当传入switch的是null时,在运行时对一个null调用hashCode()方法,会抛出NullPointerException;如果case写的是null,那么在编译时无法求出hashcode,就会编译报错。
0 0
- Switch用String做参数
- Switch用String做参数
- Switch能否用string做参数
- Switch能否用string做参数?
- Switch能否用String做参数
- Switch能否用String做参数
- Switch能否用String做参数?
- switch能否用String做参数?
- 2. Switch能否用String做参数?
- Switch能否用string做参数
- Switch能否用String做参数?
- Switch能否用string做参数
- 2. Switch能否用String做参数?
- Switch能否用string做参数?
- switch可以用string做参数吗?
- Switch能否用string做参数?
- Switch能否用string做参数?
- 在Java7中Switch用String做参数
- Java源码剖析 sun.misc.Unsafe
- Array运用
- 从字符串中提取逐一提取数字id
- 芒果iOS开发之格式转化符总结
- JavaScript中的运算操作陷阱
- Switch用String做参数
- OCX控件中界面如何捕获键盘消息
- maven打jar例子
- Android WebView打开https地址错误的问题
- Unreal4 简单创建一个c++项目,并给对象添加材质
- 黑马程序员——C语言基础08—结构体/枚举
- js/jQuery效果集锦
- NSThread、NSOperation、GCD、NSOperationQueue
- setEmptyView