一、append(int i),來自StringBuffer的父類AbstractStringBuilder源碼
步驟:
1、圍觀源碼
public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
// stringSizeOfInt,判斷輸入的整數i占多少位,如負數+1,方法源碼往後看。
int appendedLength = (i < 0) ? stringSizeOfInt(-i) + 1
: stringSizeOfInt(i);
int spaceNeeded = count + appendedLength;
if (spaceNeeded > value.length) // 檢查容量,是否需擴容
expandCapacity(spaceNeeded);
Integer.getChars(i, spaceNeeded, value); // 把整型i以字元的形式加進buffer(value)中,getChars源碼較複雜,暫時未看。
count = spaceNeeded; //更新count長度。
return this;
}
2、圍觀占位表和整數占位算法。
//占位表
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,99999999, 999999999, Integer.MAX_VALUE };
// Requires positive x
static int stringSizeOfInt(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i]) // 無限循環将整型x與占位表逐一對比,例如x=100,将與占位表索引為2的999比對。
return i+1; //傳回2+1,占3位。
}
3、順便多看一下append(long l)的源碼,其實内部原理跟append(int i)原理一樣。
// Requires positive x
static int stringSizeOfLong(long x) {
long p = 10;
for (int i=1; i<19; i++) {
if (x < p) // 與兩位數10比較,小于傳回占一位
return i;
p = 10*p; //如此類推,小于100占2位
}
return 19; // 最大19位
}