Integer源码学习(Byte、Long同理)

# 底层存储
``` 
private final int value;
public Integer(int value) {
    this.value = value;
}
```
即Integer内部持有一个int类型的常量,在调用Integer构造器时会对此常量赋值,而且这个值不可改变,从构造器实现可以知道,每次通过new关键字创建Integer类型都是一个新的对象,即new Integer(1) != new Integer(1)。
# 静态内部类IntegerCache
```
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
        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);
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
            }
        }
        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 IntegerCache.high >= 127;
    }
    private IntegerCache() {}
}
```
首先看IntegerCache的属性,从属性中可以看到,low值时固定的-128,high值不固定,cache[]数组待初始化。
再看静态代码块实现逻辑,可以知道high默认为127,但是可以通过JVM属性值进行修改,然后cache[]数组会通过low-high进行初始化,并赋予相应值。
Integer包装类即通过此种方式实现对-128-127(默认)区间返回的值进行缓存,进而达到节约没存的目的。
# valueOf()静态方法
```
public static Integer valueOf(int i) {
    if(i >= IntegerCache.low && i <=IntegerCahce.high) {
        return IntegerCahce.chache[i+(-IntegerChace.low)];    
    }
    retrun new Integer(i);
}
```
从代码可以看到,对于通过调用valueOf(i)方式获得的Integer类型实例,会首先判断实例数据是否已经缓存在IntegerCahce对象中,如果已经被缓存,则直接从缓存中取值,否则,通过new关键字返回新的对象。
另一方面,Integer i = 1这种赋值方式,实际上在代码运行时是通过调用valueOf(i)方法实现的,所以通过此方式可以利用到缓存,进而一下代码的执行结果会是true。
```
public boolean compare() {
    Integer i = 1;
    Integer j = 1;
    return i == j;
}
```
# 疑惑点
IntegerCache类的类初始化时机
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值