Integer应该用==还是equals

问题引出:“Integer应该用==还是equals”

讨论这个问题之前我们先放一段代码

public static void main(String[] args) {

Integer a1 = 2;
Integer a2 = 2;
System.out.println(a1==a2); //true
System.out.println(a1.equals(a2)); //true

Integer a3 = 127;
Integer a4 = 127;
System.out.println(a3==a4); //true
System.out.println(a3.equals(a4)); //true

Integer a5 = -128;
Integer a6 = -128;
System.out.println(a5==a6); //true
System.out.println(a5.equals(a6)); //true
/**
* ----
* */
Integer a11 = 128;
Integer a21 = 128;
System.out.println(a11==a21); //false
System.out.println(a11.equals(a21)); //true


Integer a1111 = -129;
Integer a2111 = -129;
System.out.println(a1111==a2111);//false
System.out.println(a1111.equals(a2111)); //true
}

上述代码可以看出 值相同的Integer对象做==操作,有的是true,有的是false,而equals操作的一直是true,为什么会出现这种情况?

我们首先解释==操作,为什么有的是true,有的是false:

  讨论之前:先要知道对象的==操作,比较的是对象的地址

   对于 Integer var = ? -128 127 范围内的赋值, Integer 对象是在IntegerCache.cache 产生,会复用已有对象,比如a1和a2,他们都是指向的同一块内存空间

对象的==操作,比较的是"地址",所以对于-128 至 127 范围内的Integer 对象,值相同的integer对象都是指向的同一块内存空间,所以这个区间内的 Integer 值可以

直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产生,并不会复用已有对象,这是一个大坑

 我们再来解释equals,为什么一直是true:

对象的equals,比较的是对象的值,所以只要值相同的Integer对象,使用equals比较的结果,都会是true

 

posted @ 2019-04-11 11:17  明日中午  阅读(3381)  评论(0编辑  收藏  举报