128陷阱,自动装箱自动拆箱中的那些坑

上期我们讲过自动拆箱自动装箱是JDK1.5之后的新特性
下面我们讲讲关于这里的一个“128陷阱”

public static void main(String[] args) {
   Integer k=100;
               //Integer是一个引用数据类型,又是一个对象
               //100默认是一个基本数据类型
               //我们相当于把基本数据类型赋值给一个对象
               //  对象  = 基本数据类型
  Integer m=100;
  int i=100;
  Integer j=new Integer(100);
System.out.println("k和m比较");
System.out.println(k==m);//ture
//ture,证明两个Integer同时指向了常量池中的100(缓存机制)
System.out.println("k和 i 比较");
System.out.println(k==i);//ture
//ture,证明Integer和int指向常量池的100
System.out.println("k和 j 比较");
System.out.println(k==j);//false
//false,证明new方法出来的integer对象在堆中,引用地址不同为false
   Integer a = 127;
   Integer b = 127;
   Integer c = 128;
   Integer d = 128;
System.out.println("a和b比较");
System.out.println(a == b);//ture
System.out.println("c和d ==比较");
System.out.println(c == d);//false
//证明只有-128~127(128陷阱)会加载到常量池中,其他会在堆中开辟不同空间
System.out.println("c和d .intValue()比较");
System.out.println(c.intValue() == d.intValue());//ture
//ture,证明也可以主动调用拆箱方法使得Integer的值可以比较
System.out.println("c和d equals比较");
System.out.println(c.equals(d));//ture
//true,证明integer重写了equals()方法,我们可以用来比较
    }

我们先猜一下输出true还是false
在这里插入图片描述

在这里插入图片描述

这里可以看出在int的包装类Integer在127以及之前的时候是可以使用==去判断两个数是否相等的,而在Integer是128的时候就不能去判断这两个数是否相等。
这里涉及自动拆箱自动装箱

Integer k=100;//自动装箱机制
//相当于进行下面这一步
Integer k=Integer.valueOf(100);

这里我们好奇为什么c和d比较为什么返回false
如果要问他的原因,让我们读一下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);
}

我们发现,IntegerCache.low和IntegerCache.high可以在上面代码定义中看到,定义的为-128和127,看代码可知,如果这个数 i 实在-128到127之间则直接返回这个已经定义在数组中的值,而不再这个范围中则需要去new一个新的对象,我们知道在java中==比较是储存对象的地址,在大于等于128的情况下他其实是new了两个对象
用 = =判断自然是不可取的,因为他是俩对象,结果返回自然是false,这里我们要判断应该是使用equals。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值