先看代码
@Test public void testEquals() { int int1 = 12; int int2 = 12; Integer integer1 = new Integer(12); Integer integer2 = new Integer(12); Integer integer3 = new Integer(127); Integer a1 = 127; Integer a2 = 127; Integer a = 128; Integer b = 128; System.out.println("int1 == int2 -> " + (int1 == int2)); //true System.out.println("int1 == integer1 -> " + (int1 == integer1)); //true System.out.println("integer1 == integer2 -> " + (integer1 == integer2)); //false System.out.println("integer3 == a1 -> " + (integer3 == a1)); //false System.out.println("a1 == a2 -> " + (a1 == a2)); //true System.out.println("a == b -> " + (a == b));//false }
- 首先int1=int2不需要解释了
- int1==integer1是因为Integer与int比较时会自动拆箱成int。这里的Integer不管是直接赋值还是new出来的对象。只要是和int比较都会自动拆箱。
- integer1和integer2两者都是对象,不会拆箱。所以不相等