A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 谭景宾 中级黑马   /  2012-5-7 20:21  /  1681 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Integer i1=33;
Integer i2=33;
System.out.println(i1==i2); //这时候为true
但是当
Integer i1=333;
Integer i2=333;
System.out.println(i1==i2); //这时候为false

这是因为一旦把-128~127之间的数字包装成Integer之后,程序就会把这之间的数字缓存起来,
下次再包装之后先看缓存里有没有,有的话直接从缓存里拿,所以导致了-128~127之间的数字为true
其余的数字为false。

有点不理解为什么只把-128~127之间的数缓存起来??而不把其余所有的数字都缓存起来?
java又是用什么方法把-128~127之间的数字缓存起来的?底层原理是什么?

评分

参与人数 1技术分 +1 收起 理由
贠(yun)靖 + 1

查看全部评分

2 个回复

倒序浏览
本帖最后由 隋营营 于 2012-5-7 21:20 编辑

这种问题可以直接看 Integer 类的源代码:
Integer类中有一个内部类IntegerCache,它的实现很能说明问题!
    /**
     * 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() {}
    }

    /***
    *......................................................................
    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
   
    /**
    *.......................................

IntegerCache类有一个静态的Integer数组,在Integer类加载时就创建了一个Integer对象(数值在-128~127之间,最大值可以根据property设定),保存在cache数组中。
若valueOf()方法被调用,若Integer对象的值在-128 到 127 之间,就直接在cache缓存数组中去取!

个人猜想之所以不把所有字节都缓存起来是为了节约内在空间!
非常感谢对认识不到的地方给予指正!

评分

参与人数 1技术分 +1 收起 理由
贠(yun)靖 + 1

查看全部评分

回复 使用道具 举报
学习了,呵呵
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马