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