比较两个Integer的int值是否相等

来源:互联网 发布:知乎boy scout 编辑:程序博客网 时间:2024/05/22 10:54

    • Prerequisite
    • Track
    • Summarize

Prerequisite

大致的情况是这样的:在一个项目中要比较两个Integer的int值是否相等,我直接使用Integer的自动装箱特性new出对象

代码如下:Integer integer1=1;Integer integer2=1;System.out.println(integer1==integer2);Integer integer3=245;Integer integer4=245;System.out.println(integer3==integer4);输出:falsefalse

第二个输出为false!这是要搞事啊!debug跟踪一下

Track

1、打好断点
这里写图片描述
2、step into后,竟然跑到valueOf方法去了。先不管IntegerCache是什么鬼,大概浏览一下代码可知该方法所做的是,若你要自动包装的数值在某个区间,则返回已经缓存好的对象,否则重新new一个对象,因此不同的对象当然不相等惹!
这里写图片描述
3、看IntegerCache这个内部类的介绍和代码,英文不四很好,大概的意思四IntegerCache的作用是把-128~127的值缓存起来。IntegerCache会最先被初始化,缓存数值范围可以通过-XX:AutoBoxCacheMax配置。

     /**     * Cache to support the object identity semantics of autoboxing for values between     * -128 and 127 (inclusive) as required by JLS.     *     * The cache is initialized on first usage.  The size of the cache     * may be controlled by the -XX:AutoBoxCacheMax=<size> option.     * During VM initialization, java.lang.Integer.IntegerCache.high property     * may be set and saved in the private system properties in the     * sun.misc.VM class.     */    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));            }            high = h;            cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);        }        private IntegerCache() {}    }

Summarize

综上所述,在利用Integer的自动包装特性包装数值时,默认情况下,若值位于-128~127之间,则对应的Integer对象已存在缓存中,否则JVM会重新new一个Integer对象。如果要比较两个Integer的int值是否相等,需使用Integer的equals方法。

原创粉丝点击