这是因为整数缓存。
来自java language specification 5.1.7
If the value p being boxed is true, false, a byte, or a char in the range
\u0000 to \u007f, or an int or short number between -128 and 127 (inclusive),
then let r1 and r2 be the results of any two boxing conversions of p.
It is always the case that r1 == r2.
理想情况下,对给定的原始值 p 进行装箱,将始终产生相同的引用。
Integer i = Integer.valueOf(127);
Integer j = Integer.valueOf(127);
i和j都指向同一个对象。因为值小于127。
Integer k = Integer.valueOf(128);
Integer l = Integer.valueOf(128);
k 和 l 都指向不同的对象。因为值大于 127。
当您使用 == 运算符检查对象引用时,您会得到不同的结果。
更新
你可以使用equals()方法得到同样的结果
System.out.println(i.equals(j));//equals() compares the values of objects not references
System.out.println(k.equals(l));//equals() compares the values of objects not references
输出是
true
true
-
== 运算符检查实际的对象引用。
-
equals() 检查对象的值(内容)。
回复评论
你有,
Integer i = Integer.valueOf(127);
这里创建了新对象并将引用分配给i
Integer j = Integer.valueOf(127); //will not create new object as it already exists
由于整数缓存(-128 到 127 之间的数字),先前创建的对象引用被分配给 j,然后 i 和 j 指向相同的对象。
现在考虑,
Integer p = Integer.valueOf(127); //create new object
Integer q = Integer.valueOf(126); //this also creates new object as it does not exists
显然,使用== 运算符和equals() 方法进行的检查都会产生false。因为两者都是不同的引用,并且具有不同的值。