關於常量池

2021-09-13 23:13:32 字數 2676 閱讀 4599

這裡暫且把integer作為包裝類的代表來說明.

我們知道每次new都是建立乙個新的物件,由於==比較的是記憶體位址,所以下面的**不會為true:

string s1 = new string("1");

string s2 = new string("1");

system.out.println(s1 == s2); //false

但是下面的**可以為true,用到的就是常量池.多長的字串都可以:

string s3 = "1";

string s4 = "1";

system.out.println(s4 == s3);//true

string sl1 = "qwertyuiopasdfghjkl;'zxcvbnm,./";

string sl2 = "qwertyuiopasdfghjkl;'zxcvbnm,./";

system.out.println(sl1 == sl2);//true

但是在integer中,情況有所不同(new的情況下一定是false,這裡不做測試):

integer i1 = 100;

integer i2 = 100;

system.out.println(i1 == i2);//true

integer i3 = 192;

integer i4 = 192;

system.out.println(i3 == i4);//false

integer i5 = -100;

integer i6 = -100;

system.out.println(i5 == i6);//true

integer i7 = -192;

integer i8 = -192;

system.out.println(i7 == i8);//false

這裡利用了自動裝箱的特性,我們知道自動裝箱呼叫的是integer.valueof(int i),我們來看看這個方法裡面的邏輯:

public static integer valueof(int i)
這"乙個值"是什麼值? 

有個ingetercache,cache在計算機中代表快取的意思,那麼這個東西是不是就是integer的"快取"?來看看原始碼: 

private static class integercache  catch(numberformatexception nfe) 

}11-> high = h;

12-> cache = new integer[(high - low) + 1];

13-> int j = low;

for(int k = 0; k < cache.length; k++)

14-> cache[k] = new integer(j++);

// range [-128, 127] must be interned (jls7 5.1.7)

15-> assert integercache.high >= 127;

}private integercache() {}

}

integercache是integer類中的乙個私有內部類,按照標識的數字來解釋:

1.low(可以理解為下限)是-128.

2.定義乙個high(可以理解為上限),但是未賦值.

3.定義乙個陣列cache(池),尚未初始化,valueof返回的值就是這個陣列元素的型別:int.

4.可以通過配置讀取high的值.

5.變數h,值為127(預設上限).

6.看起來是通過配置檔案讀取值.

7.讀取到的值不為空,不是合法的數字就丟擲數字格式異常.

8.將讀取到的值轉換為int.

9.轉換後的值與127之中找乙個較大值.

10.乙個是i,乙個是ingeter最大值減去負的low(即128)再減去1,這兩個值取較小值,賦值給h.

11.high賦值為h.

12.cache被初始化為容量大小為high + 128 + 1的陣列(多的那個1大概是用來儲存0?).

13.定義乙個變數j,值為-128(low).

14.從j到high依次新增進cache.

15.這裡使用了斷言:只要high不符合大於等於127的條件,就退出,並丟擲assertionerror.

可以看出,常量池最小的範圍是-128到127,但是可以由我們自定義.如果定義的值在cache中,就直接返回int值,也就是在常量池內的兩個值==為true的原因:基本資料型別直接比較.否則就返回新建的integer物件.

下面給出long的常量池longcache**,可以看出範圍是固定的-128到127,不能修改,short,byte也是一樣的.

private static class longcache 

static final long cache = new long[-(-128) + 127 + 1];

static

}

double,float沒有這些**. 

快取常量池

亞信面試題 先說結論 integer a 127 integer b 127 integer c 128 integer d 128 a b true c d false integer a new integer 127 integer b new integer 127 integer c ne...

測試常量池

那天學些了常量池的一些特性,寫了一些 來驗證理論.1 public class testconstantspool 56 static void stringpool 1920 128 127以內的integer值 21static void integerpool 3132 33 128 127以...

常量池隨筆

常量池儲存了類,介面,方法等的常量資料,也儲存了string常量.如下 中a1,a2不是string常量 在編譯期即被確定 a3則是,a1.intern 也可以獲得string常量 是在執行時被裝載的常量 string a1 new string a a2 new string a string a...