面試 Integer與int詳解

2021-09-28 12:32:42 字數 3429 閱讀 3701

一說明

int為4 位元組大小(一位元組8位),其大小相當於2的32次方(4,294,967,296)精確範圍包括負數除以2得到範圍為-2,147,483,648~2,147,483,647(21億左右);

int 是基本資料型別,integer是引用型別;

integer是int的包裝型別

integer預設值為 null, int 預設值為0;

public static void main(string args)
這個結果很容易確定,youku1 和 youku3 是 引用型別 ,他們在堆上分配位址,所以 youku1不等於youku3

當youku1和youku3與youku2比較的時候會自動拆箱,所以youku1等於youku2,youku2等於yoouku3。

示例:

public static void main(string args)
我們對上面的**進行位元組碼編譯(如下圖)發現youku1變數呼叫了intvalue()方法那麼我們可以得出結論,integer的自動拆箱是呼叫integer.intvalue()方法:

驗證自動拆箱:

// 自動拆箱

@test

public void inttest()

原始碼如下:

/**

* the value of the .

** @serial

*/private final int value;​

​/**

* returns the value of this as an

* .*/

public int intvalue()

示例:

public static void main(string args)
​位元組碼編譯結果(如下圖)可得youku2這個這個變數是個靜態類變數,直接在初始化類的時候載入了,經過呼叫integer.valueof()自動裝箱為integer物件,再經過integer.intvalue()自動拆箱跟youku1​相比較。

驗證自動裝箱:

// 自動裝箱

@test

public void int2test()

原始碼如下:

/**

* returns an instance representing the specified

* value. if a new instance is not

* required, this method should generally be used in preference to

* the constructor , as this method is likely

* to yield significantly better space and time performance by

* caching frequently requested values.

** this method will always cache values in the range -128 to 127,

* inclusive, and may cache other values outside of this range.

** @param i an value.

* @return an instance representing .

* @since 1.5

*/public static integer valueof(int i) ​

/*** constructs a newly allocated object that

* represents the specified value.

** @param value the value to be represented by the

* object.

*/public integer(int value)

注:this method will always cache values in the range -128 to 127,

inclusive, and may cache other values outside of this range.

這個方法一直快取 -128~127 之間的值,也可能快取這個範圍之外的值

這個沒啥好說的,引用物件在堆上分配的位址不同,物件不相等。

//  new integer 和 new integer 之間的比較

@test

public void int3test()

youku1 是個 堆上分配的物件,youku2是個常量池分配的變數(之前自動裝箱的位元組碼編譯也看見了是直接載入到棧裡面然後呼叫valueof()方法轉為integer物件),位址不一樣,物件不相等。

// new integer 和 integer 之間比較

@test

public void int4test()

下面的變數都是常量,都會進行自動裝箱也就是呼叫了integer.valueof()方法,上面的原始碼你也看見了會一直快取 -128~127 之間的值,所以youku1等於youku2,youku3不等於youku4​。​

// integer 和 integer 之間的比較

@test

public void int5test()

這其實沒啥好說的了,之前的自動裝箱和拆箱分析了,只要是int 跟這2 個比較 都會進行 自動裝箱和拆箱。

//  int 和 new integer 和 integer 之間 的比較

Integer 與int 賦值比較

測試 test public void integertest 執行結果 true true false true 斷點除錯分析結果 i01是引用型別,如圖引用的位址為integer 651 i02是值型別 i03是引用型別,因為引用型別值放在堆裡面,如果堆裡有值,i03這種取值方式就直接引用原有值...

Integer 與int 賦值比較

測試 test public void integertest 執行結果 true true false true 斷點除錯分析結果 i01是引用型別,如圖引用的位址為integer 651 i02是值型別 i03是引用型別,因為引用型別值放在堆裡面,如果堆裡有值,i03這種取值方式就直接引用原有值...

int與integer的區別

1.所佔記憶體不同 integer物件會占用更多的記憶體。integer是乙個物件,需要儲存物件的元資料。但是int是乙個原始型別的資料,所以占用的空間更少。2.型別及初始值 int 是基本型別,直接存數值,在類進行初始化時int類的變數初始為0 而integer是物件 integer是int的封裝...