Auto-Boxing 的问题

这是CSDN上的一个帖子,问题如下:

public static void main(String[] args) {

        Integer a = 128;

        Integer b = 128;

        System.out.println(a == b);

    }

请问输出结果是什么,并给出解释。

——————————————————————————-

输出结果为:false,分析如下:

首先,看看Integer的封装吧:

    public static Integer valueOf(int i) {

          final int offset = 128;

          if (i >= -128 && i <= 127) { // must cache

             return IntegerCache.cache[i + offset];

          }

           return new Integer(i);

        }
当你直接给一个Integer对象一个int值的时候,其实它调用了valueOf方法,然后你赋的这个值很特别,是128,那么没有进行cache方法,相当于new了两个新对象。所以问题中定义ab的两句代码就类似于:

        Integer a = new Integer(128);

        Integer b = new Integer(128);
这个时候再问你,输出结果是什么?你就知道是false了。如果把这个数换成127,再执行:

        Integer a = 127;

        Integer b = 127;

        System.out.println(a == b);
结果就是:true

由上可知,我们进行对象比较时最好还是使用equals,便于按照自己的目的进行控制。

————————————————–补充———————————————————————–

我们看一下IntegerCache这个类里面的内容:

    private static class IntegerCache {

       private IntegerCache() {

       }

       static final Integer cache[] = new Integer[-(-128) + 127 + 1];

       static {

           for (int i = 0; i < cache.length; i++)

              cache[i] = new Integer(i – 128);

       }

    }

由于cache[]在IntegerCache类中是静态数组,也就是只需要初始化一次,即static{……}部分,所以,如果Integer对象初始化时是-128~127的范围,就不需要再重新定义申请空间,都是同一个对象—在IntegerCache.cache中,这样可以在一定程度上提高效率。

类似文章:JAVA中具有实例缓存的不可变类

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment