Integer a = 1; Integer b = 1;

Integer a = 1;
Integer b = 1;
Integer c = 500;
Integer d = 500;
System.out.println(a == b);
System.out.println(c == d);
Integer aa=new Integer(10);
Integer bb=new Integer(10);
int cc=10;
System.out.println(aa == bb);
System.out.println(aa == cc);



答案是
true
false
false
true

Integer a = 1;是自动装箱会调用Interger.valueOf(int)方法;该方法注释如下:
This method will always *** values in the range -128 to 127 inclusive, and may *** other values outside of this range.
也就是说IntegerCache类缓存了-128到127的Integer实例,在这个区间内调用valueOf不会创建新的实例。
Integer类型在-128-->127范围之间是被缓存了的,也就是每个对象的内存地址是相同的,赋值就直接从缓存中取,不会有新的对象产生,而大于这个范围,将会重新创建一个Integer对象,也就是new一个对象出来,当然地址就不同了,也就!=;

一、包装类和基本数据类型在进行“==”比较时,包装类会自动拆箱成基本数据类型,integer(0)会自动拆箱,结果为true

二、两个integer在进行“==”比较时,如果值在-128和127之间,结果为true,否则为false

三、两个包装类在进行“equals”比较时,首先会用equals方法判断其类型,如果类型相同,再继续比较值,如果值也相同,则结果为true

四、基本数据类型如果调用“equals”方法,但是其参数是基本类型,此时此刻,会自动装箱为包装类型

原文地址:https://www.cnblogs.com/zhuyeshen/p/12106071.html