聊聊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ā)中,版本迭代是最常見也是能夠很好權衡開發(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利用validation實現(xiàn)優(yōu)雅的校驗參數(shù)
數(shù)據(jù)的校驗是交互式網(wǎng)站一個不可或缺的功能,如果數(shù)據(jù)庫中出現(xiàn)一個非法的郵箱格式,會讓運維人員頭疼不已。本文將介紹如何利用validation來對數(shù)據(jù)進行校驗,感興趣的可以跟隨小編一起學習一下2022-06-06
java ConcurrentHashMap分段加鎖提高并發(fā)效率
這篇文章主要為大家介紹了java ConcurrentHashMap分段加鎖提高并發(fā)效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
java操作mongodb之多表聯(lián)查的實現(xiàn)($lookup)
這篇文章主要介紹了java操作mongodb之多表聯(lián)查的實現(xiàn)($lookup),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

