-128-127自动装箱时的陷阱

package cn.itcast.demo;
import java.util.Date;
/*
 * Integer类的内部有一个IntegerCache缓存类;
 * 实际上就是缓存了一个大小为256的Integer数组;
         把-128 ~ 127之间的所有Integer对象都提前创建好,缓存在数组中,方便后面使用;
         目的是为了提高性能和节约空间;
         当定义一个不在-128 ~ 127之间的Integer对象时,会新创建一个Integer对象
 */
public class DateDemo {
	public static void main(String[] args) {
		Integer i = 10; // -128 ~ 127
		Integer i2 = 10;
		Integer i3 = 127;
		Integer i4 = 127;
		Integer i5 = 128;
		Integer i6 = 128;
		System.out.println(i == i2);// true
		System.out.println(i3 == i4);// true
		System.out.println(i5 == i6);// false      比较的是两个对象的地址
		System.out.println(i5.equals(i6)); //true  比较的是两个对象的内容
	}
}

//IntegerCache缓存类的源代码
/*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) {
            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);
        }
        high = h;

        cache = new Integer[(high - low) + 1];  //缓存了一个大小为256的Integer数组
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);  //该数组里面装了256个Integer类型的对象
    }
    private IntegerCache() {}
}*/
                                                                                                            2018.4.15 长沙


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值