我不允许你还不会的——Java中Integer和int的相关比较

1. Integer与int类型的关系

Integer是int的包装类,int的默认值是0,而Integer的默认值是null(我们经常在代码中使用的Integer.valueOf() 和xx.intValue()就是自动装箱和拆箱的过程

需要注意的是Integer里面默认的缓存数字是-128—127

  • Integer与Integer相互比较,数据在【-128,127】范围内,就会从缓存中拿去数据,比较就相等;如果不在这个范围,就会直接新创建一个Integer对象,使用== 判断的是两个内存的应用地址,所以自然不相等。

  • Integer和int类型相比,在jdk1.5,会自动拆箱,然后比较栈内存中的数据

关于这两点,先有个印象,下面会进行详细讲解

注意,必须是Integer j = 100这种,不能是Integer j = new Integer(100)

2. int跟int比较

int数据类型,都是在栈内存中存储,如果这个数字在栈内存中存在就会直接指向这个内存地址,如果不存在,就会重新开辟内存空间,

所以,int和int类型的比较,相同的值不会存在内存不等的情况

八个基本数据类型不能看作对象(这点很特殊),存放在栈中。栈内操作速度快,创建销毁很容易

3. int跟Integer比较

会自动拆箱,变成int与int对比

4. Integer类型的比较

Integer类型的比较是面试中常问的一个东西,如果深入了解其中也大有学问,涉及基本数据类型,引用数据类型的装箱拆箱,类加载机制等。还有就是,我们做算法题的时候,如果不知道Integer类型的比较规则,要花费很大功夫才能找到测试用例不通过多的原因。

首先看下面代码的执行结果

public class TestInteger {
    public static void main(String[] args) {
        Integer i1 = 100;
        Integer i2 = 100;
        System.out.println(i1 == i2);

        Integer i3 = 200;
        Integer i4 = 200;
        System.out.println(i3 == i4);

		System.out.println(i3.equals(i4));
    }
}

在这里插入图片描述

为什么变量是100和200时会出现上述的结果呢?

首先要明白Integer i1 = 100做了什么? 在做这样的操作时,实际就是基本数据类型与引用类型之间的拆箱和装箱操作,Integer i1 = 100是一个装箱操作,本质就是Integer i1 = Integer.valueOf(100),源码如下

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

valueOf方法中,对赋的值进行一个判断操作,如果值在【-128,127】之间,就会在内部类IntegerCachecache[]数组中获取一个Integer对象,如果不是就,new一个新的Integer对象。注意,只有Integer i = 1这样的语句,会从cache中获取对象,如果是Integer i = new Integer(1),会直接创建对象。


那么cache[]中又是什么呢?

看一下Integer类中的静态内部类IntegerCache源码

 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中的一段源码中可以发现cache[]中循环放入了值在【-128,127】之间的Integer对象,根据内部类加载机制,当类第一

次调用时会初始化这个数组,并且在JVM中只初始化一次,到这里我们就明白了为什么赋值在【-128,127】之间的比较时能够相等,因为==

比较的是内存地址,示例代码中的变量i1和i2在这个范围内都引用了从cache取出的同一个对象,对象内存地址一样,所以是相等的,在超出

这个范围之后,每次创建会new一个新的Integer对象,引用的是不同的对象,所以不相等。


那为什么equals方法一直相等呢?

public boolean equals(Object obj) {
   if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

可以看到Integerequals方法进行重写,从比较两个对象的内存地址变成了比较两个Integer对象的的值,这与String类相似,

同时重写的还有hashCode()方法,hashcode返回了对象的值


那为什么要设计IntegerCache类来缓存-128~127的对象呢?

节省内存消耗,提高程序性能,Integer是一个经常使用到的类,并且一般创建的对象值范围都在-128~127之间,并且创建这样相似值的对

象并没有太大意义,所以使用IntegerCache类,再看其它的包装器:

  • Boolean:(全部缓存)
  • Byte:(全部缓存)

  • Character(<= 127缓存)
  • Short(-128 — 127缓存)
  • Long(-128 — 127缓存)

  • Float(没有缓存)
  • Doulbe(没有缓存)

那Integer比较用什么方法呢?

推荐compareTo方法,其次equals方法

总结

  • 无论如何,Integernew Integer不会相等。不会经历拆箱过程.
  • 两个都是非new出来的Integer,如果数在-128到127之间,则是true,否则为false
  • java在编译Integer i2 = 128的时候,被翻译成Integer i2 = Integer.valueOf(128),而valueOf()函数会对-128到127之间的数进行缓存
  • 两个都是new出来的,都为false
  • intIntegernew Integer()进行==比较时,值相等就为true,因为会把Integer自动拆箱为int再去比

参考

如有不足之处,欢迎指正,谢谢!

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值