代码
1 @Slf4j 2 public class IntegerCompare { 3 public static void doCompare() { 4 5 Integer a = 127; //Integer.valueOf(127) 6 Integer b = 127; //Integer.valueOf(127) 7 log.info(" Integer a = 127; " + 8 "Integer b = 127; " + 9 "a == b ? {}", a == b); // true 10 11 Integer c = 128; //Integer.valueOf(128) 12 Integer d = 128; //Integer.valueOf(128) 13 log.info(" Integer c = 128; " + 14 "Integer d = 128; " + 15 "c == d ? {}", c == d); //false 16 17 Integer e = 127; //Integer.valueOf(127) 18 Integer f = new Integer(127); //new instance 19 log.info(" Integer e = 127; " + 20 "Integer f = new Integer(127); " + 21 "e == f ? {}", e == f); //false 22 23 Integer g = new Integer(127); //new instance 24 Integer h = new Integer(127); //new instance 25 log.info(" Integer g = new Integer(127); " + 26 "Integer h = new Integer(127); " + 27 "g == h ? {}", g == h); //false 28 29 Integer i = 128; //unbox 30 int j = 128; 31 log.info(" Integer i = 128; " + 32 "int j = 128; " + 33 "i == j ? {}", i == j); //true 34 } 35 }
结果:
Integer a = 127; Integer b = 127; a == b ? true 2020-04-13 22:30:47.162 INFO 4492 --- [ restartedMain] com.example.newdemo.IntegerCompare : Integer c = 128; Integer d = 128; c == d ? false 2020-04-13 22:30:47.162 INFO 4492 --- [ restartedMain] com.example.newdemo.IntegerCompare : Integer e = 127; Integer f = new Integer(127); e == f ? false 2020-04-13 22:30:47.162 INFO 4492 --- [ restartedMain] com.example.newdemo.IntegerCompare : Integer g = new Integer(127); Integer h = new Integer(127); g == h ? false 2020-04-13 22:30:47.162 INFO 4492 --- [ restartedMain] com.example.newdemo.IntegerCompare : Integer i = 128; int j = 128; i == j ? true
结论:
-
=比较的是引用
-
equal比较的是integer实际的值
第一个相等,第二个不相等,是因为Interger.valueOf内部做了缓存(-127,127)。
- a, b相同的引用。
- c,d超过了缓存的范围直接new,产生不同的引用,所以不相等。
Integer e = 127;
Integer f = new Integer(127);
e从缓存中读取。f则是新的对象,用=判断时候是两个不同的引用,所以不相等。
Integer g = new Integer(127);
Integer h = new Integer(127);
g和h都是新的引用。
Integer i = 128;
int j = 128;
把装箱的 Integer 和基本类型 int 比较,前者会先拆箱再比较,比较的肯定是数值而不是引用,因此返回 true