switch对String的支持
Java 7中,switch的参数可以是String类型了,这对我们来说是一个很方便的改进。到目前为止切换支持这样几种数据类型: 一,开关对整型支持的实现下面是一段很简单的Java的代码,定义一个INT型变量一个,然后使用切换语句进行判断。执行这段代码输出内容为5,那么我们将下面这段代码反编译,看看他到底是怎么实现的。 public class switchDemoInt { public static void main(String[] args) { int a = 5; switch (a) { case 1: System.out.println(1); break; case 5: System.out.println(5); break; default: break; } } } //output 5 反编译后的代码如下: public class switchDemoInt { public switchDemoInt() { } public static void main(String args[]) { int a = 5; switch(a) { case 1: // ‘ 01‘ System.out.println(1); break; case 5: // ‘ 05‘ System.out.println(5); break; } } } 我们发现,反编译后的代码和之前的代码比较除了多了两行注释以外没有任何区别,那么我们就知道,切换对int的判断是直接比较整数的值。 二,开关对字符型支持的实现直接上代码: public class switchDemoInt { public static void main(String[] args) { char a = ‘b‘; switch (a) { case ‘a‘: System.out.println(‘a‘); break; case ‘b‘: System.out.println(‘b‘); break; default: break; } } } 编译后的代码如下:`public class switchDemoChar public class switchDemoChar { public switchDemoChar() { } public static void main(String args[]) { char a = ‘b‘; switch(a) { case 97: // ‘a‘ System.out.println(‘a‘); break; case 98: // ‘b‘ System.out.println(‘b‘); break; } } } 通过以上的代码作比较我们发现:对字符类型进行比较的时候,实际上比较的是ASCII码,编译器会把炭型变量转换成对应的INT型变量 三,开关对字符串支持的实现还是先上代码: public class switchDemoString { public static void main(String[] args) { String str = "world"; switch (str) { case "hello": System.out.println("hello"); break; case "world": System.out.println("world"); break; default: break; } } } 对代码进行反编译: public class switchDemoString { public switchDemoString() { } public static void main(String args[]) { String str = "world"; String s; switch((s = str).hashCode()) { default: break; case 99162322: if(s.equals("hello")) System.out.println("hello"); break; case 113318802: if(s.equals("world")) System.out.println("world"); break; } } } 看到这个代码,你知道原来字符串的开关是通过 好,以上就是关于开关对整型,字符型,和字符串型的支持的实现方式,总结一下我们可以发现,其实切换只支持一种数据类型,那就是整型,其他数据类型都是转换成整型之后在使用开关的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |