1. 程式人生 > >【java】switch case支持的7種數據類型

【java】switch case支持的7種數據類型

包裝類 mac 打開 拆箱 創建 eval get trade ocs

switch表達式後面的數據類型只能是byte,short,char,int四種整形類型,枚舉類型和java.lang.String類型(從java 7才允許),不能是boolean類型。

在網上看到好多文章,說switch還支持byte,short,char,int 的包裝類,首先可以肯定說switch不支持這些包裝類,但是如下的代碼又是正確的:

    public static void main(String[] args) {
        switch (new Integer(45)) {
        case 40:
            System.out.println(
"40"); break; case 45: System.out.println("45");//將會打印這句 break; default: System.out.println("?"); break; } }

可以打印正確的結果,在挨著挨著試完Byte,Short,Character,Integer後發現都可以正確打印,於是便說switch也支持byte,short,char,int的包裝類。這種說法不完全正確,之所以switch能夠支持他們的包裝類,是因為自動拆箱(就是自動將引用數據類型轉化為基本數據類型)的原因,下面使用jclasslib軟件打開上面的.class文件,

 1 0 new #2 <java/lang/Integer>                             創建一個Integer類的對象
 2 3 dup                                                    將對象的標識壓入棧頂部
 3 4 bipush 45                                              將整形45壓入棧中
 4 6 invokespecial #3 <java/lang/Integer.<init>>            調用Integer類型的構造方法
5 9 invokervirtual #4 <java/lang/Integer.intValue> 調用intValue()方法 6 12 lookupswitch 2 7 40:40(+28) 8 45:51(+39) 9 defalut:62(+50) 10 40 getstatic #5 <java/lang/System.out> 獲得標準輸出流 11 43 ldc #6 <40> 從常量池中將40的索引壓入棧中 12 45 invokevirtual #7 <java/io/PrintStream.println> 調用println()方法 13 48 goto 70 (+22) 14 51 gestatic #5 <java/lang/System.out> 15 54 ldc #8 <45> 16 56 invokevirtual #7 <java/io/PrintStream.println> 17 59 goto 70 (+11) 18 62 getstatic #5 <java/lang/System.out> 19 65 ldc #9<?> 20 67 invokevirtual #7 <java/io/PrintStream.println> 21 70 return

從上面的第5行我們可以看出編譯器自動調用了intValue()方法,如果是使用Byte會自動調用byteValue()方法,如果是Short會自動調用shortValue()方法,如果是Integer會自動調用intValue()方法。switch 的查找原理是使用key-offset在目標表格中查找的,lookupswitch後面的數字和goto後面的數字都是有規律的,關於更多信息可以查看The Java® Virtual Machine Specification

因此switch表達式後面的數據類型只能是byte,short,char,int四種整形類型,枚舉類型和java.lang.String類型。

【java】switch case支持的7種數據類型