菜鸟笔记
提升您的技术认知

在switch语句中使用字符串以及实现原理

一次机缘巧合,在idea中调试代码的时候,跳到了.class文件中,刚好调试的代码是switch,于是就有了下面的内容:

对于Java语言来说,在Java 7之前,

switch语句中的条件表达式的类型只能是与整数类型兼容的类型,包括基本类型char、byte、short和int,与这些基本类型对应的封装类Character、Byte、Short和Integer,

还有枚举类型。这样的限制降低了语言的灵活性,使开发人员在需要根据其他类型的表达式来进行条件选择时,不得不增加额外的代码来绕过这个限制。为此,Java 7放宽

了这个限制,额外增加了一种可以在switch语句中使用的表达式类型,那就是很常见的字符串,即String类型。

源代码:

[java]  view plain copy

  1. public class TestSwitch {  
  2.     public static void main(String[] args) {  
  3.         test("a");  
  4.     }  
  5.   
  6.     public static void test(String type) {  
  7.         switch (type) {  
  8.         case "a":  
  9.             System.out.println("aa");  
  10.             break;  
  11.         case "b":  
  12.             System.out.println("bb");  
  13.   
  14.             break;  
  15.         }  
  16.     }  
  17.   
  18. }  

[java]  view plain copy

  1. public class TestSwitch {  
  2.     public static void main(String[] args) {  
  3.         test("a");  
  4.     }  
  5.   
  6.     public static void test(String type) {  
  7.         switch (type) {  
  8.         case "a":  
  9.             System.out.println("aa");  
  10.             break;  
  11.         case "b":  
  12.             System.out.println("bb");  
  13.   
  14.             break;  
  15.         }  
  16.     }  
  17.   
  18. }  

编译后的.class文件:

[java]  view plain copy

  1. import java.io.PrintStream;  
  2.   
  3. public class TestSwitch  
  4. {  
  5.   
  6.     public TestSwitch()  
  7.     {  
  8.     }  
  9.   
  10.     public static void main(String args[])  
  11.     {  
  12.         test("a");  
  13.     }  
  14.   
  15.     public static void test(String type)  
  16.     {  
  17.         String s;  
  18.         switch((s = type).hashCode())  
  19.         {  
  20.         default:  
  21.             break;  
  22.   
  23.         case 97: // 'a'  
  24.             if(s.equals("a"))  
  25.                 System.out.println("aa");  
  26.             break;  
  27.   
  28.         case 98: // 'b'  
  29.             if(s.equals("b"))  
  30.                 System.out.println("bb");  
  31.             break;  
  32.         }  
  33.     }  
  34. }  

从代码可以看出,java虚拟机实际上是将字符串转化为哈希值,还是利用整数类型兼容的类型来进行判断,但是哈希值可能存在值相等的情况,所以又对字符串进行了2次比较。

总结:switch能判断字符串是因为将字符串做了哈希运算,本质上还是数字,java虚拟机没有变化,只是编译器发生了变化。

 不过值得一提的是,通过这件事,给我们提供了一种新的思路,通过查看编译后的java文件,来探究底层实现方法。