基于jdk1.8的Java源碼詳解 Integer
public final class Integer extends Number implements Comparable<Integer>
Integer 由final修飾了,所以該類不能夠被繼承,同時 Integer 繼承了Number類,因此可以將Integer轉(zhuǎn)換成 int 、double、float、long、byte和short類型的數(shù)據(jù),另外,也實現(xiàn)了comparable接口,因此Integer類也可以進行自然排序。
構(gòu)造方法只有兩個:
public Integer(int value) {
this.value = value;
}
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
我們主要看第二個構(gòu)造方法,傳入一個字符串,然后調(diào)用parseInt方法,接下來進入parseInt的源碼:
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
// //是否為負數(shù)
boolean negative = false;
int i = 0, len = s.length();
//這里加個負號是防止數(shù)據(jù)溢出,int的數(shù)值范圍 -2的31次方到2的31次方減一
int limit = -Integer.MAX_VALUE;
//最小基數(shù)
int multmin;
//十進制數(shù)字
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
//第一個字符小于0,有可能是"-","+"或其他字符
if (firstChar < '0') { // Possible leading "+" or "-"
//為負數(shù)
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')//非數(shù)字
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
/**
* 最小基數(shù),主要防止 result *= radix; 這個操作時數(shù)據(jù)過大
* 導(dǎo)致數(shù)據(jù)丟失的問題,因為所以帶符號32位int類型整數(shù)為-2147483648~2147483647
*/
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
//轉(zhuǎn)換十進制,這里獲取的是radix進制下相對應(yīng)的10進制數(shù)字,如:
//Character.digit('a',16),則返回 10;
//若輸入字符不在進制的范圍之內(nèi),則返回 -1:
//Character.digit('t',16),返回 -1,Character.digit('a',10),返回 -1
digit = Character.digit(s.charAt(i++),radix);
//返回-1說明字符非法
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
//超過了數(shù)據(jù)范圍
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
/**
*在轉(zhuǎn)換時從高位向地位方向轉(zhuǎn)換
*/
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
這個方法中最核心的步驟是1、result *= radix; 2、result -= digit; 經(jīng)過這兩個步驟將字符串轉(zhuǎn)換成數(shù)值類型。大概流程是這樣的:
- 假如字符串"1234" 轉(zhuǎn)換成int類型,result 的初始值為0,radix默認為10;
- 首先截取字符串的第一個字符1(這里忽略各種檢查),經(jīng)過第一步計算 result = 0*10 = 0;第二部計算 result = 0 - 1 = -1;
- 第一遍循環(huán)結(jié)束后,result 的值 變成了 -1
- 截取第二個字符 2 ,result = -1 * 10 = -10,result = -10 - 2 = -12;
- 截取第三個字符 3 ,result = -12 * 10 = -120,result = -120 - 3 = -123;
- 截取第四個字符 4 ,result = -123 * 10 = -1230 ,result = -1230-4 = -1234;
- 循環(huán)結(jié)束,此時result的值為 -1234,完成字符串向整數(shù)型的轉(zhuǎn)換,返回是取反即可。
面我將從一個面試題引出問題,然后通過閱讀源碼來解決這個問題。
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
Integer i5 = Integer.valueOf(100);
Integer i6 = Integer.valueOf(100);
Integer i7 = new Integer(100);
System.out.println("i1 == i2 的結(jié)果是:" + (i1 == i2));
System.out.println("i3 == i4 的結(jié)果是:" + (i3 == i4));
System.out.println("i5 == i6 的結(jié)果是:" + (i5 == i6));
System.out.println("i1 == i5 的結(jié)果是:" + (i1 == i5));
System.out.println("i1 == i7 的結(jié)果是:" + (i1 == i7));
}
運行結(jié)果為:
i1 == i2 的結(jié)果是:true i3 == i4 的結(jié)果是:false i5 == i6 的結(jié)果是:true i1 == i5 的結(jié)果是:true i1 == i7 的結(jié)果是:false
我們先來看第一和第二條結(jié)果,同樣是比較兩個相同數(shù)值,為什么會有不同的結(jié)果呢?接下我將通過源碼來解釋原因。
首先,我們通過編譯獲取到class文件的字節(jié)碼

從圖中我們可以看到,在執(zhí)行 Integer i1 = 100 這條命令的時候,編譯器會調(diào)用Integer中的靜態(tài)方法 valueOf,接下來我們看看 valueOf方法是怎么實現(xiàn)的吧。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
這個代碼看起來很簡單,Integer 中有一個靜態(tài)內(nèi)部類 IntegerCache,調(diào)用該方法時首先會判斷該值是否在緩存的范圍內(nèi),如果在則直接將緩存中的數(shù)值返回,否則返回一個新對象。看到這里我們似乎已經(jīng)知道了上面的問題的答案了,接下來繼續(xù)看靜態(tài)內(nèi)部類吧
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
//緩存范圍最?。ㄒ彩悄J范圍)為 (-128)~ 127,如果配置java.lang.Integer.IntegerCache.high
//high 的值可從配置文件中讀取
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
//獲取配置文件和127之間的最大值
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
//最大值范圍
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
//創(chuàng)建緩存數(shù)組
cache = new Integer[(high - low) + 1];
int j = low;
//將數(shù)字緩存起來默認 -128 ~ 127
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
我們知道內(nèi)部類只有在所在類實例化時才會被實例化,而且只會實例化一次,緩存操作是在靜態(tài)代碼塊中完成,也就是說在類被實例化的時候數(shù)據(jù)就已經(jīng)被緩存好了,接下使用的時候可以直接使用緩存的數(shù)據(jù)。
現(xiàn)在我們回歸到上面的問題,結(jié)果1中兩個數(shù)據(jù)均為 100,在緩存的范圍中,因此i1和i2都指向的是同一個內(nèi)存地址,因此返回true。結(jié)果2中 兩個數(shù)都是200,超出了緩存的范圍,所以直接new 出了兩個對象,因此他們的內(nèi)存地址不一致,返回結(jié)果為false;另外,使用valueOf 和 使用 = 操作符賦值時一樣的,所以結(jié)果3和結(jié)果4返回結(jié)果為 true,結(jié)果5中 是直接使用new關(guān)鍵字創(chuàng)建對象,所以他們的內(nèi)存地址肯定不一致,結(jié)果為false。
那么,現(xiàn)在問題又來了,那我怎么判斷兩個整數(shù)的大小呢?繼續(xù)看源碼
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
public int intValue() {
return value;
}
是的,沒錯,比較兩個數(shù)值大小時可以使用equals方法來比較,源碼中value的類型為 int型,intValue返回的也是value,因此可以判斷兩個數(shù)的大小。
public static void main(String[] args) {
Integer i1 = 200;
Integer i2 = 200;
System.out.println("i1 == i2 的結(jié)果是:" + i1.equals(i2)); //true
}
補充:equals 與 == 的區(qū)別:
equals 比較的是兩個數(shù)值的大小,== 有兩種情況,如果比較的是 基本數(shù)據(jù)類型,則 == 跟equals一樣都是比較的大小,如果是引用類型或數(shù)組,則比較是內(nèi)存地址。
getChars方法:
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration
//每次循環(huán)獲取后兩位數(shù)
while (i >= 65536) {
q = i / 100;
// really: r = i - (q * 100);
//使用位移運算的效率高于乘法運算,r為后兩位數(shù)
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
//獲取后兩位數(shù)的個位
buf [--charPos] = DigitOnes[r];
//十位
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
//每次只取個位數(shù)
for (;;) {
//相當(dāng)于i*(52429/524288)=i*0.10000038146972656=i*0.1=i/10
//這里選 52429 和 2的19次方相除,得到的結(jié)果精度更加高,更加接近于 i/10的結(jié)果
//之所以要這樣轉(zhuǎn)換,是因為在計算機運算中位移的效率 > 乘法效率 > 除法效率
q = (i * 52429) >>> (16+3);
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring MVC Controller返回值及異常的統(tǒng)一處理方法
這篇文章主要給大家介紹了關(guān)于Spring MVC Controller返回值及異常的統(tǒng)一處理方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者使用Spring MVC具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
IDEA使用JDBC導(dǎo)入配置jar包連接MySQL數(shù)據(jù)庫
這篇文章介紹了IDEA使用JDBC安裝配置jar包連接MySQL數(shù)據(jù)庫的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-12-12
Java優(yōu)先隊列(PriorityQueue)重寫compare操作
這篇文章主要介紹了Java優(yōu)先隊列(PriorityQueue)重寫compare操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java編寫程序之輸入一個數(shù)字實現(xiàn)該數(shù)字階乘的計算
這篇文章主要介紹了Java編寫程序之輸入一個數(shù)字實現(xiàn)該數(shù)字階乘的計算,本文通過實例代碼給大家介紹的非常想詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
使用try-with-resource的輸入輸出流自動關(guān)閉
這篇文章主要介紹了使用try-with-resource的輸入輸出流自動關(guān)閉方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

