Java中的128陷阱

public static void main(String[] args){

    Integer a=128;    
    Integer b=128;

    System.out.print(a==b);//false
    a=127;
    b=127;
    System.out.print(a==b);//true
}

为什么对于一个Integer来说,两个Integer都为128的时候通过==判断为false,127时的==却是true呢?

其实这一切都是因为Java中的装箱和拆箱机制,每一个基本类型都对应有自己的类,如int和Integer,double和Double等.在Integer类中有个valueOf(int i)方法,拆箱就是通过Integer的这个静态方法执行的一系列操作.

在这个方法中涉及到了IntegerCache这个类中类,在这个类中声明了low和high这两个静态常量,其中low是-128,high没有设置默认值.

看见low和high再结合128陷阱对int的范围,就能想到了,这个low和high就是控制范围的,那么high会在哪初始化呢?

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) {
                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() {}
    }

在加载IntegerCache类的时候执行了该类中的所有static字段,其中在static块中声明并且初始化了h变量为127(???127不就是拆箱的最大值吗),为什么还要多次一举呢?其实在这里有个非常牛批的设定,那就是程序员可以自己设定这个high的大小.

在JVM的设置项中添加以下的句子.

-Djava.lang.Integer.IntegerCache.high=250;

所以说设置之后,变量i读取后值为250大于127,但是又小于Integer.MAX_VALUE - (-low) -1,所以high设置成功,从现在开始所有的-127~250的Integer都不是对象,而是存储在常量池cache中,即IntegerCache.cache,从源码中我们也可以看到cache的大小为(high-low)+1.

好,现在我们就把Integer的问题说清楚了,但是这么做有什么实际意义呢?

其实就是省去了建立过多的对象,比如在淘宝中,127以下的商品有很多,假如把他们都存成Integer对象的话就会占用过多的内存,此时把低于127的存储在数组中就可以省去很多的内存开销.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值