JDK源码解析之 java.lang.Integer
teger 基本數(shù)據(jù)類型int 的包裝類
Integer 類型的對象包含一個 int 類型的字段
一、類定義
public final class Integer extends Number implements Comparable<Integer>{}- 類被聲明為final的,表示不能被繼承;
- 繼承了Number抽象類,可以用于數(shù)字類型的一系列轉(zhuǎn)換;
- 實現(xiàn)了Comparable接口,強行對實現(xiàn)它的每個類的對象進行整體排序
二、成員變量
//保持 int類型的最大值的常量可取的值為 231-1。 @Native public static final int MIN_VALUE = 0x80000000;//保持 int類型的最小值的常量可取的值為-231。 @Native public static final int MAX_VALUE = 0x7fffffff;//表示基本類型 int 的Class 實例。 @SuppressWarnings("unchecked")public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");//以二進制補碼形式表示 int 值的位數(shù)。 @Native public static final int SIZE = 32; public static final int BYTES = SIZE / Byte.SIZE;三、構(gòu)造器
// 構(gòu)造一個新分配的 Integer 對象,它表示指定的 int 值。 public Integer(int value) {this.value = value;}// 構(gòu)造一個新分配的Integer 對象,它表示 String 參數(shù)所指示的 int 值。 public Integer(String s) throws NumberFormatException {this.value = parseInt(s, 10);}四、常用方法
1、parseInt(String s, int radix)
Integer(String s)引用的靜態(tài)方法,進制轉(zhuǎn)換的公式:a * radix^0 + b * radix^1 + c * radix^2 + … + xx * radix^(n-1)
public static int parseInt(String s, int radix) throws NumberFormatException{//如果轉(zhuǎn)換的字符串如果為null,直接拋出空指針異常if (s == null) {throw new NumberFormatException("null");}//如果轉(zhuǎn)換的radix(默認是10)<2 則拋出數(shù)字格式異常,因為進制最小是 2 進制if (radix < Character.MIN_RADIX) {throw new NumberFormatException("radix " + radix +" less than Character.MIN_RADIX");}//如果轉(zhuǎn)換的radix(默認是10)>36 則拋出數(shù)字格式異常,因為0到9一共10位,a到z一共26位,所以一共36位//也就是最高只能有36進制數(shù)if (radix > Character.MAX_RADIX) {throw new NumberFormatException("radix " + radix +" greater than Character.MAX_RADIX");}int result = 0;boolean negative = false;int i = 0, len = s.length();//len是待轉(zhuǎn)換字符串的長度int limit = -Integer.MAX_VALUE;//limit = -2147483647int multmin;int digit;//如果待轉(zhuǎn)換字符串長度大于 0if (len > 0) {char firstChar = s.charAt(0);//獲取待轉(zhuǎn)換字符串的第一個字符//這里主要用來判斷第一個字符是"+"或者"-",因為這兩個字符的 ASCII碼都小于字符'0'if (firstChar < '0') {if (firstChar == '-') {//如果第一個字符是'-'negative = true;limit = Integer.MIN_VALUE;} else if (firstChar != '+')//如果第一個字符是不是 '+',直接拋出異常throw NumberFormatException.forInputString(s);if (len == 1) //待轉(zhuǎn)換字符長度是1,不能是單獨的"+"或者"-",否則拋出異常throw NumberFormatException.forInputString(s);i++;}multmin = limit / radix;//通過不斷循環(huán),將字符串除掉第一個字符之后,根據(jù)進制不斷相乘在相加得到一個正整數(shù)//比如 parseInt("2abc",16) = 2*16的3次方+10*16的2次方+11*16+12*1//parseInt("123",10) = 1*10的2次方+2*10+3*1while (i < len) {digit = Character.digit(s.charAt(i++),radix);if (digit < 0) {throw NumberFormatException.forInputString(s);}if (result < multmin) {throw NumberFormatException.forInputString(s);}result *= radix;if (result < limit + digit) {throw NumberFormatException.forInputString(s);}result -= digit;}} else {//如果待轉(zhuǎn)換字符串長度小于等于0,直接拋出異常throw NumberFormatException.forInputString(s);}//根據(jù)第一個字符得到的正負號,在結(jié)果前面加上符號return negative ? result : -result; }2、toString() toString(int i) toString(int i, int radix)
public String toString() {return toString(value); }public static String toString(int i) {if (i == Integer.MIN_VALUE)return "-2147483648";int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);char[] buf = new char[size];getChars(i, size, buf);return new String(buf, true); }*/public static String toString(int i, int radix) {if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)radix = 10;/* Use the faster version */if (radix == 10) {return toString(i);}char buf[] = new char[33];boolean negative = (i < 0);int charPos = 32;if (!negative) {i = -i;}while (i <= -radix) {buf[charPos--] = digits[-(i % radix)];i = i / radix;}buf[charPos] = digits[-i];if (negative) {buf[--charPos] = '-';}return new String(buf, charPos, (33 - charPos));}toString(int) 方法內(nèi)部調(diào)用了 stringSize() 和 getChars() 方法,stringSize() 它是用來計算參數(shù) i 的位數(shù)也就是轉(zhuǎn)成字符串之后的字符串的長度,內(nèi)部結(jié)合一個已經(jīng)初始化好的int類型的數(shù)組sizeTable來完成這個計算。
3、stringSize(int x)
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,99999999, 999999999, Integer.MAX_VALUE };// Requires positive xstatic int stringSize(int x) {for (int i=0; ; i++)if (x <= sizeTable[i])return i+1;}實現(xiàn)的形式很巧妙。注意負數(shù)包含符號位,所以對于負數(shù)的位數(shù)是 stringSize(-i) + 1。
4、getChars(int i, int index, char[] buf)
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 iterationwhile (i >= 65536) {q = i / 100;// really: r = i - (q * 100);r = i - ((q << 6) + (q << 5) + (q << 2));i = q;buf [--charPos] = DigitOnes[r];buf [--charPos] = DigitTens[r];}// Fall thru to fast mode for smaller numbers// assert(i <= 65536, i);for (;;) {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;}}5、equals(Object obj)
這個方法很簡單,先通過 instanceof關(guān)鍵字判斷兩個比較對象的關(guān)系,然后將對象強轉(zhuǎn)為 Integer,在通過自動拆箱,轉(zhuǎn)換成兩個基本數(shù)據(jù)類 int,然后通過 == 比較。
public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false; }6、hashCode() 方法
public int hashCode() {return value;}7、compareTo(Integer anotherInteger) 和 compare(int x, int y)
compareTo 方法內(nèi)部直接調(diào)用 compare 方法:
public int compareTo(Integer anotherInteger) {return compare(this.value, anotherInteger.value);} public static int compare(int x, int y) {return (x < y) ? -1 : ((x == y) ? 0 : 1);}如果 x < y 返回 -1,如果 x == y 返回 0,如果 x > y 返回 1
8、內(nèi)部類IntegerCache
IntegerCache為Integer類的緩存類,默認緩存了-128~127的Integer值,如遇到[-128,127]范圍的值需要轉(zhuǎn)換為Integer時會直接從IntegerCache中獲取
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127;String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}}high = h;cache = new Integer[(high - low) + 1];int j = low;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() {} }五、拓展
1、一道面試題
Integer a1 = 100;Integer a2 = 100;Integer a3 = 1000;Integer a4 = 1000;System.out.println(a1==a2);System.out.println(a3==a4);輸出答案,分別是true和false,我們知道Integer是int的包裝類,所以a1,b1.c1,d1都是引用變量,比較的是地址,但為什么在等于100和1000的時候結(jié)果不一樣呢?
通過查看源碼知道,Integer在對-128-127之間的數(shù)進行了緩存,就是說之前我創(chuàng)建了a1為100,而當創(chuàng)建a2的時候自動指向a1的地址,所以就不難解釋為什么a1==a2為true了。
總結(jié)
以上是生活随笔為你收集整理的JDK源码解析之 java.lang.Integer的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu7.10中的apache的一
- 下一篇: k8---proxy