只是了解一些皮毛,知道自动装箱会调用如Integer.valueOf() 或者拆箱调用如 .intValue(),但是结合如下代码仍有一些不理解
public class Test{
public static void main(String[] args){
int first;
Integer second;
Integer third;
first = 127;
second = 127;
third = 127;
System.out.printf("%s%n",(first == second));
System.out.printf("%s%n",(second == third));
first = 128;
second = 128;
third = 128;
System.out.printf("%s%n",(first == second));
System.out.printf("%s%n",(second == third));
}
}
输出结果是:
true
true
true
false
对于这个为什么会得到这样的结果仍旧不太理解,希望前辈们多多指教
首先,对于两个
(first == second)
,因为 first 是 int(基本类型),所以在进行 == 比较的时候,second 会从Integer
拆箱为int
,然后 == 进行的是值比较 —— 因为两次值(第一次都为 127,第二次都为 128)都相等,所以两次都是true
;在看两个

(second == third)
,second 和 third 都是Integer
(对象),所以 == 比较的时候,比较的是对象的引用,如果两个引用指向的是同一块内存(同一个对象),那么返回true
,否则返回false
。second = 127;
这样的代码其实是 Java 的语法糖,真正执行的是second = Integer.valueOf(127)
,我们来看看Integer.valueOf
的源码:很容易理解,
Integer
的内部缓存了 IntegerCache.low ~ IntegerCache.high 的Integer
,所以如果传入的整数参数 i 在这个范围之内的话,那么返回的就是缓存的对象,否则才新建一个Integer
。在 Oracle 的 JVM 上,Integer
的缓存范围默认为 -128 ~ 127。所以每次调用Integer.value(127)
返回的都是同一个被缓存的Integer
,而调用Integer.value(128)
将每次新建一个Integer(new Integer(128))
。所以第一个(second == third)
返回 true,第二个返回 false。