Java的自动装箱与自动拆箱
生活随笔
收集整理的這篇文章主要介紹了
Java的自动装箱与自动拆箱
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:什么是自動裝箱拆箱
裝箱就是自動將基本數據類型轉換為包裝器類型;
拆箱就是自動將包裝器類型轉換為基本數據類型。
java中需要裝箱拆箱的類型如下:
| int(4字節) | Integer |
| byte(1字節) | Byte |
| short(2字節) | Short |
| long(8字節) | Long |
| float(4字節) | Float |
| double(8字節) | Double |
| char(2字節) | Character |
| boolean(未定) | Boolean |
二:測試代碼分析
public class IntegerTest {public static void main(String[] args) {Integer a = new Integer(10);int b = 10;System.out.println(a == b);} }結果打印:
true執行反編譯:javap -c IntegerTest
E:\WorkSpace\Git\sortalgorithm-demos\target\classes\com\leo\demo\othertest>javap -c IntegerTest 警警告告: 二二進進制制文文件件IntegerTest包包含含com.leo.demo.othertest.IntegerTest Compiled from "IntegerTest.java" public class com.leo.demo.othertest.IntegerTest {public com.leo.demo.othertest.IntegerTest();Code:0: aload_01: invokespecial #1 // Method java/lang/Object."<init>":()V4: returnpublic static void main(java.lang.String[]);Code:0: new #2 // class java/lang/Integer3: dup4: sipush 2207: invokespecial #3 // Method java/lang/Integer."<init>":(I)V10: astore_111: sipush 22014: istore_215: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;18: aload_119: invokevirtual #5 // Method java/lang/Integer.intValue:()I22: iload_223: if_icmpne 3026: iconst_127: goto 3130: iconst_031: invokevirtual #6 // Method java/io/PrintStream.println:(Z)V34: return }以上轉換使用了
Method java/lang/Integer.intValue:()此方法的源碼如下:
/*** 這個方法會緩存-128到127的數的對象,如果不在這個區間則重新生成新的對象* This method will always cache values in the range -128 to 127,*/public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}三:測試裝拆箱緩存對象
根據上面的分析,如果是使用valueOf方法則會緩存-128—127的對象,那做如下測試:
public class IntegerTest {public static void main(String[] args) {Integer a1 = 10;Integer a2 = 10;Integer a3 = new Integer(10);Integer a4 = new Integer(10);System.out.println("a1 == a2 返回 "+(a1 == a2));System.out.println("a1 == a3 返回 "+(a1 == a3));System.out.println("a3 == a4 返回 "+(a3 == a4));System.out.println("------分割線------");Integer c1 = 200;Integer c2 = 200;Integer c3 = new Integer(200);Integer c4 = new Integer(200);System.out.println("c1 == c2 返回 "+(c1 == c2));System.out.println("c1 == c3 返回 "+(c1 == c3));System.out.println("c3 == c4 返回 "+(c3 == c4));} }打印結果:
a1 == a2 返回 true a1 == a3 返回 false a3 == a4 返回 false ------分割線------ c1 == c2 返回 false c1 == c3 返回 false c3 == c4 返回 false結論,如果使用Integer a1 = 10;這種方式使用裝箱操作使用的就是valueOf方法實現的。當-128—127時返回的是同一對象,不在此范圍的生成了新的對象。
四:其他包裝類緩存范圍
歸類:
Integer系列:Integer、Short、Byte、Character、Long這幾個類的valueOf方法的實現是類似的。
Double系列:Double、Float的valueOf方法的實現是類似的。每次都返回不同的對象。
針對Integer總結緩存范圍,如下:
| Integer | [-128,127] |
| Short | [-128,127] |
| Character | c<=127 |
| Long | [-128,127] |
最后注意,比較兩個包裝類型數值大小要使用equals方法
總結
以上是生活随笔為你收集整理的Java的自动装箱与自动拆箱的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: J.U.C系列(四)FutrueTask
- 下一篇: 手写一个简单的线程池MyThreadPo