int类型和Integer类型数据的比较

一、由于Integer变量实际上是对一个Integer对象的引用,所以两个通过new生成的Integer变量永远是不相等的(因为new生成的是两个对象,其内存地址不同)。

例子1:

Integer a5 = new Integer(-128);
Integer a6 = new Integer(-128);
System.out.println(a5 == a6);

运行结果:

二、Integer变量和int变量比较时,只要两个变量的值是向等的,则结果为true(因为包装类Integer和基本数据类型int比较时,java会自动将Integer拆箱为int,然后进行比较,实际上就变为两个int变量的比较)

举例2:

int a8 = -129;
Integer a9 = new Integer(-129);
System.out.println(a8 == a9);

运行结果:

三、非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。(因为非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同)

举例3:

Integer num1 = -128;
Integer num2 = new Integer(-128);
System.out.println(num1 == num2);

运行结果: 

四、对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false

举例4:

Integer a1 = -128;
Integer a2 = -128;
System.out.println(a1 == a2);
System.out.println("=============");
Integer a3 = -129;
Integer a4 = -129;
System.out.println(a3 == a4);

运行结果: 

原理分析:

Integer i1 = 20 或者Integer i1 = 200的时候,会调用 Integer中的 valueOf()方法。我们看一下这个方法的源码:

	/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

这段代码的作用是把int类型转换成Integer,也就是装箱,它返回一个 Integer对象。
这里又涉及到IntegerCache,对于这段静态代码(这里JDK版本是JDK1.8):

	/**
     * 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 {@code -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) {
                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() {}
    }

这段代码的作用是,在Integer类装载入内存时,把[-128, 127]范围内的整型数据装包成Integer类,并将其对应的引用放入到cache数组中。

从上面的源码可以看出,valueOf()在返回之前,会进行判断,判断当前 i的值是否在 -128到127之间。
如果存在,则直接返回引用,不再重新开辟内存空间。
如果不存在,就创建一个新的对象。
利用缓存,这样做既能提高程序执行效率,还能节约内存。

Integer i1 = 20; Integer i2 = 20; 因为 IntegerCache中已经存在此对象,直接返回引用,引用相等并且都指向缓存中的数据,所以这时候i1 == i2返回true。

Integer i1 = 200; Integer i2 = 200;因为i1,i2的值大于127,不在[-128, 127]范围内,所以虚拟机会在堆中重新new一个 Integer对象来存放200,创建两个对象就会产生两个这样的空间。两个空间的地址不同,返回到栈中的引用的值也就不同,所以这时候i1 == i2返回false。

参考文章: Java中Integer.valueOf()解读_shboli的博客-CSDN博客_integer.valueof()作用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值