說說switch關鍵字

Switch語法switch作為Java內置關鍵字 , 卻在項目中真正使用的比較少 。關于switch,還是有那么一些奧秘的 。
要什么switch,我有if-else確實,項目中使用switch比較少的一個主要原因就在于它的作用能被if-else代替,況且switch對類型的限制,也阻礙了switch的進一步使用 。
先看看switch的語法:
switch(exp){case exp1:break;case exp2:break;default:break;}其中exp的類型限制為:byte ,short , int , char,及其包裝類 , 以及枚舉和String(JDK1.7)
為什么要有這些限制?如果說,switch的功能和if-else的一模一樣,那么它存在的意義在哪里?
答案是:switchif-else在設計的時候 , 是有一定的性能差別的 。
看代碼:
public class Test {public static void switchTest(int a) {switch (a) {case 1:System.out.println("1");break;case 2:System.out.println("2");break;default:System.out.println("3");break;}}}javap  -c Test.class 結果如下:public static void switchTest(int);Code:0: iload_01: lookupswitch{ // 21: 282: 39default: 50} ...這里面省略一些代碼 。
可以發現,switch是通過lookupswitch指令實現 。那么lookupswitch指令是干嘛的呢?
在Java se8文檔中的描述可以大概知道:
switch可以被編譯為兩種指令

  • lookupswitch:當switchcase比較稀疏的時候,使用該指令對int值的case進行一一比較 , 直至找到對應的case(這里的查找,可以優化為二分查找)
  • tableswitch:當switchcase比較密集的時候,使用case的值作為switch的下標,可以在時間復雜度為O(1)的情況下找到對應的case(可以類比HashMap)
并且文檔中還有一段描述:
The Java Virtual Machine's tableswitch and lookupswitch instructions operate only on int data. Because operations on byte, char, or short values are internally promoted to int, a switch whose expression evaluates to one of those types is compiled as though it evaluated to type int. If the chooseNear method had been written using type short, the same Java Virtual Machine instructions would have been generated as when using type int. Other numeric types must be narrowed to type int for use in a switch.
大概翻譯如下: Java 虛擬機的 tableswitchlookupswitch 指令僅對 int 數據進行操作 。因為對 bytecharshort 值的操作在內部被提升為 int , 所以其表達式計算為這些類型之一的 switch 被編譯為好像它計算為 int 類型 。如果使用 short 類型編寫了 chooseNear 方法,則將生成與使用 int 類型時相同的 Java 虛擬機指令 。其他數字類型要在switch中使用必須轉為int類型 。
現在,我們應該能夠明白,為什么switch關鍵字會有類型限制了 , 因為 switch所被翻譯的關鍵字是被限制為int類型的,至于為什么是int,我猜應該是基于性能和實現的復雜度的考量吧 。
int之外的類型我們明白了byte,shor,char,int能被作為switch類型后 , 再看看枚舉和String
public static void switchTest(String a) {switch (a) {case "1":System.out.println("1");break;case "2":System.out.println("2");break;default:System.out.println("3");break;}}編譯生成Test.class 。拖入IDEA進行反編譯得到如下代碼:
public static void switchTest(String a) {byte var2 = -1;switch(a.hashCode()) {case 49:if (a.equals("1")) {var2 = 0;}break;case 50:if (a.equals("2")) {var2 = 1;}}switch(var2) {case 0:System.out.println("1");break;case 1:System.out.println("2");break;default:System.out.println("3");}}可以看見,JDK7 所支持的String類型是通過獲取StringhashCode來進行選擇的 , 也就是本質上還是int.為什么String可以這樣干?這取決于String是一個不變類 。
為了防止hash碰撞,自動生成的代碼中更加保險的進行了equals判斷 。
再來看看Enum
public static void switchTest(Fruit a) {switch (a) {case Orange:System.out.println("Orange");break;case Apple:System.out.println("Apple");break;default:System.out.println("Banana");break;}}

推薦閱讀