Integer应该用==仍是equals

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

讨论这个问题以前咱们先放一段代码html

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,为何会出现这种状况?spa

咱们首先解释==操做,为何有的是true,有的是false:

  讨论以前:先要知道对象的==操做,比较的是对象的地址code

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

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

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

 咱们再来解释equals,为何一直是true:

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

内存

 

原文出处:https://www.cnblogs.com/zzh-blog/p/10688492.htmlclass

相关文章
相关标签/搜索