`

StringBuffer源码浅析(append方法)

 
阅读更多

一、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位
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics