源码系列——JDK源码——包装类(Integer)

86 阅读1分钟

JDK源码

一、Integer

Integer extends Number implements Comparable<Integer> 

继承自Number并且实现比较器,Integer是基本类型int的包装类,它提供了一些处理int数值的方法,String和int相互转换的方法。Integer由final修饰,所以无法被继承。Integer继承了抽象类Number,并实现了它的下列方法: byteValue()、 shortValue()、 intValue()、 longValue() 、floatValue() 、doubleValue(),将int转换为其他基本类型的值,实现方法都是强转。

`public int compareTo(Integer anotherInteger) { return compare(this.value, anotherInteger.value); }

public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); }`

1.1 构造函数

public Integer(int value) {
    this.value = value;
}
public Integer(String s) throws NumberFormatException {
    this.value = parseInt(s, 10);
}

1.2 parseInt()

// radix 2,8,10 进制
public static int parseInt(String s, int radix)
            throws NumberFormatException
{
    if (s == null) {
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {
        throw new NumberFormatException("radix " + radix +
                                        " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;
    // '0' == 48, 48 以下都是非数字和字母 
    // '+' == 43, '-' == 45
    if (len > 0) {
        char firstChar = s.charAt(0);
        if (firstChar < '0') { // Possible leading "+" or "-"
            if (firstChar == '-') {
                negative = true;
                limit = Integer.MIN_VALUE;
            } else if (firstChar != '+')
                // 第一个字符非数字和字母,也不是 + 或者 -,抛出异常
                throw NumberFormatException.forInputString(s);

            if (len == 1) 
                // Cannot have lone "+" or "-"
                throw NumberFormatException.forInputString(s);
            i++;
        }
        multmin = limit / radix;
        while (i < len) {
            // 将 char 转换为相应进制的 int 值
            digit = Character.digit(s.charAt(i++),radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result;
}

1.3 valueOf()

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

它包含了int可能值得Integer数组,它负责存储了(high -low)个静态Integer对象,并切在静态代码块中初始化。默认范围是【-128,127】,所以这里默认只实例化了256个Integer对象,当Integer的值范围在【-128,127】时则直接从缓存中获取对应的Integer对象,不必重新实例化。这些缓存值都是静态且final的,避免重复的实例化和回收。 就是在VM加载Integer类的时候给缓存数组填充值:

-Djava.lang.Integer.IntegerCache.high=xxx

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high 可以通过启动配置进行配置
        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() {}
}

1.4 转换相应的类型

public byte byteValue() {
        return (byte)value;
    }
public short shortValue() {
        return (short)value;
    }
public int intValue() {
        return value;
    }
public long longValue() {
        return (long)value;
    }
public float floatValue() {
        return (float)value;
    }
public double doubleValue() {
        return (double)value;
    }

1.5 equals()

public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false; }

1.6 compare()

` public static int compare(int x, int y) {

return (x < y) ? -1 : ((x == y) ? 0 : 1);

} `

1.7 sum()

public static int sum(int a, int b) {
    return a + b;
}

1.8 max()

return Math.max(a, b);

1.9 min()

return Math.min(a, b);

1.10 公共字段

判断字符串的位数

final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };`
                                      
// Requires positive x
static int stringSize(int x) {
    for (int i=0; ; i++)
        if (x <= sizeTable[i])
            return i+1;
}