JDK1.8源码随笔之Integer

Integer

类图设计

在这里插入图片描述

源码摘要

toString与parseInt

public final class Integer extends Number implements Comparable<Integer> {
    // 最小值为-2的31次方
    @Native public static final int   MIN_VALUE = 0x80000000;
    // 最大值2的31次方-1
    @Native public static final int   MAX_VALUE = 0x7fffffff;

    // 初始化部分字符,在下面的数字转字符时起到检索作用
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

    /**
    * i 待转为字符的十进制数字
    * radix 要求转换进制 二进制、八进制、十六进制等,范围[2,36]
    */
    public static String toString(int i, int radix) {
        // 进制范围在2~36之间
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        if (radix == 10) {
            return toString(i);
        }

        char buf[] = new char[33];
        boolean negative = (i < 0); //i是否负数
        int charPos = 32;

        if (!negative) { //统一将i转化为负数进行操作
            i = -i;
        }

        while (i <= -radix) {
            // 检索出字符插入buf数组
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];
        // 补充i的符号
        if (negative) {
            buf[--charPos] = '-';
        }

        // 后面博客单独看看String构造器内部实现
        return new String(buf, charPos, (33 - charPos));
    }
    
    /**
     * 数值i转字符串
     */
    public static String toString(int i) {
        /**
         * i为Integer最小值则直接返回"-2147483648",此处为什么将最小值特殊处理,最大值为什么没有这样做呢?
         * Integer边界为[-2的31次方, 2的31次方-1],下面的操作中将i转为整数以确定字符长度,最小值的绝对值
         * 超过了Integer边界,sizeTable数组放不下2的31次方
         */
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
    }

    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };

    // 确定字符长度
    static int stringSize(int x) {
        for (int i=0; ; i++)
            if (x <= sizeTable[i])
                return i+1;
    }

    /**
     * 字符串转数值
     * s待转换字符串
     * radix 标识s的进制,缺省为十进制
     */
    public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        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; // 默认返回数值0
        boolean negative = false; // 是否负数
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            // 对第一位正负号等符号做处理
            if (firstChar < '0') { // ASCII比较
                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) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                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;
    }
  • 这段源码主要通过注释梳理了一下Integer类中两个常用静态方法,toString和parseInt的内部实现。类的开头即通过静态常量定义出了Integer取值范围在[MIN_VALUE, MAX_VALUE](即:[-231,231-1])。

Integer的缓存机制

Integer另一关键实现是其内部设计了一个缓存内部类IntegerCache

private static class IntegerCache {
     static final int low = -128;
     static final int high;
     static final Integer cache[];
     // 默认缓存取值范围[-128, 127]
     static {
         // 最大值通过java.lang.Integer.IntegerCache.high进行配置
         int h = 127;
         String integerCacheHighPropValue =
             sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
         if (integerCacheHighPropValue != null) {
             try {
                 int i = parseInt(integerCacheHighPropValue);
                 // 自定义最大缓存值不小于127
                 i = Math.max(i, 127);
                 // 自定义最大缓存值不大于Integer.MAX_VALUE-129
                 h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
             } catch( NumberFormatException nfe) {
                 // 自定义缓存最大值出现异常则使用默认缓存区间[-128, 127]
             }
         }
         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;
     }

那么在简洁的IntegerCache实现中,有两个明显疑问:
为什么自定义缓存最大值不能超过Integer.MAX_VALUE-129,而不是Integer.MAX_VALUE呢?
在哪些场景下可以通过IntegerCache优化性能呢?

  • 自定义缓存最大值取Integer.MAX_VALUE-129是为了在定义cache数组大小时不会超过数组length最大值
  • 通过对源码的分析,我们发现IntegerCache只有在做装箱操作时才会被调用到
/**
 * 装箱与valueOf实现一致
 */
public static Integer valueOf(int i) {
	// 缓存内直接返回,否则new一个新对象
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

如果装箱时没有命中缓存,就会在内存中重新new一个新的Integer对象。运行下面的小例子会更加的直观

  Integer n = 10;
  Integer m = 10;
  System.out.println(n == m); // true
  Integer a = 128;
  Integer b = 128;
  System.out.println(a == b); // false

设置java.lang.Integer.IntegerCache.high参数
在这里插入图片描述
重新运行后会发现128也在初始化时被缓存了
在这里插入图片描述

  • 在使用Integer做算术运算时,如果控制运算范围都能命中缓存,则运算效率将是最高的,反之则会在在内存中新建Integer对象参与隐式装箱操作,频繁算术运算下将IntegerCache范围优化可以达到客观的优化效果。

总结

      Integer是我们常用的类型之一,内部实现并不复杂,从实现的原理可以加深理解Integer的边界以及Integer的在实际场景中的优化空间,源码中大量使用了位运算,虽然对研读带来不便,但位运算大大提高了运算效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值