2.Integer源码解析

1.取值范围和基本数据类型
源码

public final class Integer extends Number implements Comparable<Integer> {
 	//该值用于定义Integer取值的最小值
    @Native public static final int   MIN_VALUE = 0x80000000;
    
    //该值用于定义Integer取值的最大值
    @Native public static final int   MAX_VALUE = 0x7fffffff;

    //该值用于定义Integer的基本数据类型
    @SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
}

源码解析

  1. Integer是被final修饰的类型,继承Number类并实现Comparable接口。
  2. Integer的最小值为-2^31 ,最大值为2^31-1。
  3. Integer的基本数据类型为int。

2.toString
源码

public final class Integer extends Number implements Comparable<Integer> {
	public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        //计算整数i的位数
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        /**
         * 将代表整数i的字符放入字符数组buf
         * 字符从指定索引处的最低有效数字(不包括最高位字符)开始向后放置
         */
        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;
    }
}

源码解析
计算Integer数的长度时,是通过构建一个一维数组,然后拿该Integer数与数组每个值进行比较。而未使用经常采用的除法来计算长度,这是因为计算机在计算除法效率要比加减乘法低,为了避免除法,提高计算效率,因此采用此种方法。

总结
在计算某个数的长度时,可以参考Integer类的stringSize()方法。

3.IntegerCache
源码

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

    static {
        int h = 127;
         //缓存的最大值是VM参数里java.lang.Integer.IntegerCache.high这个属性
        String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                //最大数组大小为Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
            } catch (NumberFormatException nfe) {
     			//如果无法将属性解析为int,则忽略它
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for (int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        assert Integer.IntegerCache.high >= 127;
    }

    private IntegerCache() {
    }
}

源码解析

  1. 初始化Integer后,IntegerCache会缓存[-128,127]之间的数据,这个区间的上限可以配置,取决于java.lang.Integer.IntegerCache.high这个属性,这个属性在VM里可以使用-XX:AutoBoxCacheMax=2000或者-Djava.lang.Integer.IntegerCache.high=2000进行调整。
  2. 在该范围内数据比较常用,添加缓存可以提高性能,不用每次都新建,浪费系统资源。同时根据Integer的hashCode方法,可以看到,Integer的hashCode返回本身的int值。

面试点

//程序1-2
public class App {
    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 1;
        Integer c = new Integer(1);
        Integer d = 1000;
        Integer e = 1000;
        System.out.println(a == b);//true
        System.out.println(b == c);//false
        System.out.println(d == e);//false
    }
}

4.valueOf和parseInt
源码

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

	public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,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;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') {
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1)
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                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. valueOf方法会从缓存中取值,如果命中缓存,会减少资源的开销。
  2. parseInt方法首先会进行异常处理,然后判断传入的String是否有正负号,截取位数后,使用乘法和减法得到int值,最后判断正负并返回结果。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值