class Integer extends Number
implements Comparable<Integer>, Constable, ConstantDesc
接口Number中需要實現(xiàn)各種類型的轉(zhuǎn)換,比如longValue、floatValue等
其他接口與String的一樣。
字符串轉(zhuǎn)換
static int stringSize(int x) {
int d = 1; //負(fù)數(shù)-標(biāo)志
if (x >= 0) { //正數(shù)轉(zhuǎn)換位負(fù)數(shù)
d = 0;
x = -x;
}
int p = -10;
//最大循環(huán)9次
for (int i = 1; i < 10; i++) {
if (x > p)
return i + d;
p = 10 * p;
}
return 10 + d;
}
在轉(zhuǎn)換字符串,計算字符串長度時,對于正負(fù)數(shù)的處理時正數(shù)變?yōu)樨?fù)數(shù)再比較。因為負(fù)數(shù)的數(shù)值比較大2的31次方,正數(shù)時2的31次方-1,所以轉(zhuǎn)換為負(fù)數(shù)。
static int getChars(int i, int index, byte[] buf) {
int q, r;
int charPos = index;
boolean negative = i < 0;
if (!negative) {
i = -i;
}
// Generate two digits per iteration
while (i <= -100) {
q = i / 100;
r = (q * 100) - i;
i = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
// We know there are at most two digits left at this point.
q = i / 10;
r = (q * 10) - i;
buf[--charPos] = (byte)('0' + r);
// Whatever left is the remaining digit.
if (q < 0) {
buf[--charPos] = (byte)('0' - q);
}
if (negative) {
buf[--charPos] = (byte)'-';
}
return charPos;
}
這里有一個while循環(huán),為了減少while循環(huán)的次數(shù),每次100取余后的結(jié)果到DigitOnes和DisgitTens數(shù)組里面直接獲取對應(yīng)的字符。例如個位字母
static final byte[] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
緩存
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
默認(rèn)緩存-128到127直接的值。也可以通過jvm啟動參數(shù)指定最大值。
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看出緩存的作用。