聊聊Java的switch為什么不支持long
Java為什么不浪(long)
學而時習之不亦說乎,繼續(xù)溫習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呢?
發(fā)現(xiàn)一個共同點,這些都是基礎數(shù)據(jù)類型中的整數(shù),并且最大不超過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的正數(shù)類型會被轉(zhuǎn)為int類型,而這一點和short、byte等類型在計算時會被轉(zhuǎn)為int來處理的表現(xiàn)是一致的。
到此為止,我們知道第一個問題的答案了。在編譯時,switch被編譯成對應的2個實現(xiàn)方式的指令,這2種指令只支持int類型。
2.為什么可支持enum和String?
按照網(wǎng)絡資料反編譯對照來看,enum最終也是轉(zhuǎn)換為enum的int序號來適應switch的。而String類型要怎么和int對應起來呢,有一種方式叫hashcode計算,最后可以得出一個數(shù)值,把這個控制在int范圍內(nèi),就能適應switch的要求了。
編程思想?yún)R總
1.類比switch支持enum和String的實現(xiàn)。
在程序開發(fā)中,由于第三方庫或者工具類中方法參數(shù)限制,調(diào)用者必須對參數(shù)做一些轉(zhuǎn)換才能調(diào)用這些方法的情況下,我們可以使用適配器模式來抹平這種差異。
2.類比switch在JDK版本在5時引入enum的支持,在7時引入對String支持。
在程序開發(fā)中,版本迭代是最常見也是能夠很好權(quán)衡開發(fā)速度和質(zhì)量的方式。類似一個App程序,我們花2年可以把它的bug數(shù)量降低到萬分之一,但市場不會留給公司那么多時間。所以實際上每家公司都是會先開發(fā)出一個有基本功能特性的App,然后沒2周或者一個月迭代一個版本,通過迭代把這個App完善好。
我們的代碼開發(fā)大家一定注意,不追求盡善盡美。先讓業(yè)務能夠跑起來,然后我們再進一步追求性能、代碼可讀性達到90甚至98分的程度。
switch能否作用于Long,string上
switch原則上只能作用于int型上,
但是,char、float、char等可以隱式的轉(zhuǎn)換為int 型,而long,string不可以,
所以呢,switch 不可以作用于Long, string 類型的變量上。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot自定義Starter與自動配置實現(xiàn)方法詳解
在Spring Boot官網(wǎng)為了簡化我們的開發(fā),已經(jīng)提供了非常多場景的Starter來為我們使用,即便如此,也無法全面的滿足我們實際工作中的開發(fā)場景,這時我們就需要自定義實現(xiàn)定制化的Starter2023-02-02Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼
這篇文章主要介紹了Springboot+AOP實現(xiàn)返回數(shù)據(jù)提示語國際化的示例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07基于mybatis?plus實現(xiàn)數(shù)據(jù)源動態(tài)添加、刪除、切換,自定義數(shù)據(jù)源的示例代碼
這篇文章主要介紹了基于mybatis?plus實現(xiàn)數(shù)據(jù)源動態(tài)添加、刪除、切換,自定義數(shù)據(jù)源,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03