聊聊Java的switch為什麼不支持long

Java為什麼不浪(long)

學而時習之不亦說乎,繼續溫習Java。

今天使用switch時,不小心寫瞭如下代碼,報錯如下。

 public static void main(String[] args) {
   long s = 20L;
   switch (s) {
   case 20L:
    System.out.println("haha");
    break;

   default:
    break;
   }
 }
/*
Cannot switch on a value of type long. Only convertible int values, strings or enum variables are permitted
*/

疑問

1.為什麼可以支持byte、char、short、int,不能支持long呢?

2.為什麼可支持enum和String?註意enum是JDK5引入,switch支持String是JDK7支持

分析

1.為什麼可以支持byte、char、short、int,不能支持long呢?

發現一個共同點,這些都是基礎數據類型中的整數,並且最大不超過int。正好去研究一下官方文檔說明。

Compilation of switch statements uses the tableswitch and lookupswitch instructions.
The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets.
The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.
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.

意思是說switch的編譯會用到兩個指令,tablesswitch和lookupswitch。而這2個指令指令隻會運行在int指令下,低於int的正數類型會被轉為int類型,而這一點和short、byte等類型在計算時會被轉為int來處理的表現是一致的。

到此為止,我們知道第一個問題的答案瞭。在編譯時,switch被編譯成對應的2個實現方式的指令,這2種指令隻支持int類型。

2.為什麼可支持enum和String?

按照網絡資料反編譯對照來看,enum最終也是轉換為enum的int序號來適應switch的。而String類型要怎麼和int對應起來呢,有一種方式叫hashcode計算,最後可以得出一個數值,把這個控制在int范圍內,就能適應switch的要求瞭。

編程思想匯總

1.類比switch支持enum和String的實現。

在程序開發中,由於第三方庫或者工具類中方法參數限制,調用者必須對參數做一些轉換才能調用這些方法的情況下,我們可以使用適配器模式來抹平這種差異。

2.類比switch在JDK版本在5時引入enum的支持,在7時引入對String支持。

在程序開發中,版本迭代是最常見也是能夠很好權衡開發速度和質量的方式。類似一個App程序,我們花2年可以把它的bug數量降低到萬分之一,但市場不會留給公司那麼多時間。所以實際上每傢公司都是會先開發出一個有基本功能特性的App,然後沒2周或者一個月迭代一個版本,通過迭代把這個App完善好。

我們的代碼開發大傢一定註意,不追求盡善盡美。先讓業務能夠跑起來,然後我們再進一步追求性能、代碼可讀性達到90甚至98分的程度。

switch能否作用於Long,string上

switch原則上隻能作用於int型上,

但是,char、float、char等可以隱式的轉換為int 型,而long,string不可以,

所以呢,switch 不可以作用於Long, string 類型的變量上。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: