Java中Integer和int值的比较

int

int是基本类型的一种
== 对于基本类型比较的是值

Integer

Integer是引用类型的一种,是int类型的包装类
== 对于引用类型比较的是内存地址

int 与 Integer 的比较

Integer i = 50;
底层调用了Integer的valueOf方法
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
对于值在-128到127之间的同一个数值放入一个缓存中,不会创建新的对象
Integer c = 5;
System.out.println("c:  " + System.identityHashCode(c));//c:  2018699554
Integer d = 5;
System.out.println("d:  " + System.identityHashCode(d));//d:  2018699554
System.out.println(c == d);// true
//System.identityHashCode(obj) 获取对象的id值,不管该对象的类是否重写了hashCode()方法
对于同一个数值的自动装箱,对象地址是一致的

对于同一个数值创建对象,其地址是不一致的
Integer a = new Integer(5);
System.out.println("a:  " + System.identityHashCode(a));//a:  2018699554
Integer b = new Integer(5);
System.out.println("b:  " + System.identityHashCode(b));//b:  1311053135
System.out.println(a == b);// false 对象比较的是内存地址
对于new Integer(5),底层创建了新的对象,对象的值为5
public final class Integer extends Number implements Comparable<Integer> {
	//...
	private final int value;
	//...
    public Integer(int value) {
        this.value = value;
    }
对于值在128及以上的Integer对象,都是重新创建的对象;值相同,内存一定不同
Integer e = 128;
System.out.println("e:  " + System.identityHashCode(e));//e:  1550089733
Integer f = 128;
System.out.println("f:  " + System.identityHashCode(f));//f:  865113938
System.out.println(e == f);// false
大于128的Integer对象和相同值的int对象的比较
两者的id值显然是不等的,但是与int类型比较时默认比较的是值
Integer f = 128;
System.out.println("f:  " + System.identityHashCode(f));//f:  865113938
int g = 128;
System.out.println("g:  " + System.identityHashCode(g));//g:  1442407170
System.out.println(g == f);// true
Integer对象之间的==操作比较的是内存地址
Integer对象之间的"<",">"等运算符操作,会将Integer先转为int再运算
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值