老白java.lang.Integer源码

  • Integer.toString(int i, int radix)
    将i转成radix进制字符串,这个方法使用了 Integer.digits数组,精髓在这里while (i <= -radix) { buf[charPos--] = digits[-(i % radix)]; i = i / radix; }
    可以使用这个方法将长的十进制id转换成长度较短的36进制id,发挥你的想象
  • Integer.valueOf(String s)
    将字符串转为Integer引用类型,其中使用到的如下方法和内部类,需要注意的是如果转为Integer的数值在缓存内的话,返回缓存对象,这会发生一些微妙的变化。举个例子,如果8在缓存里Integer.valueOf("8") == Integer.valueOf("8") 结果是true,如果888不在,结果是false
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(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
            int 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_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;

            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() {}
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章