SoEasy——你必須懂得——Java自動裝箱與拆箱

很簡單,下面兩句代碼就可以看到裝箱和拆箱過程

簡單一點說,裝箱就是自動將基本數據類型轉換為包裝器類型;拆箱就是自動將包裝器類型轉換為基本數據類型。

下面我們來看看需要裝箱拆箱的類型有哪些:

SoEasy——你必須懂得——Java自動裝箱與拆箱

這個過程是自動執行的,那麼我們需要看看它的執行過程:

1 public class Main {
2 public static void main(String[] args) {
3 //自動裝箱
4 Integer total = 99;
5
6 //自定拆箱
7 int totalprim = total;
8 }
9 }

Integer total = 99;

執行上面那句代碼的時候,系統為我們執行了:

Integer total = Integer.valueOf(99);

int totalprim = total;

執行上面那句代碼的時候,系統為我們執行了:

int totalprim = total.intValue();

就以Integer為例,來分析一下它的源碼:

1、首先來看看Integer.valueOf函數

1 public static Integer valueOf(int i) {
2 return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
3 }

它會首先判斷i的大小:如果i小於-128或者大於等於128,就創建一個Integer對象,否則執行SMALL_VALUES[i + 128]。

首先我們來看看Integer的構造函數:

1 private final int value;
2
3 public Integer(int value) {
4 this.value = value;
5 }
6
7 public Integer(String string) throws NumberFormatException {
8 this(parseInt(string));
9 }

它裡面定義了一個value變量,創建一個Integer對象,就會給這個變量初始化。第二個傳入的是一個String變量,它會先把它轉換成一個int值,然後進行初始化。

下面看看SMALL_VALUES[i + 128]是什麼東西:

 1 private static final Integer[] SMALL_VALUES = new Integer[256]; 

它是一個靜態的Integer數組對象,也就是說最終valueOf返回的都是一個Integer對象。

所以我們這裡可以總結一點:裝箱的過程會創建對應的對象,這個會消耗內存,所以裝箱的過程會增加內存的消耗,影響性能。

2、接著看看intValue函數

1 @Override
2 public int intValue() {
3 return value;
4 }

這個很簡單,直接返回value值即可。


分享到:


相關文章: