Integer a = 5; Integer b = 5; a==b的结果为true还是false?
解析:true。当整数值在 [ -128, 127 ] 范围内时,下列代码结果始终为true:
Integer a = 5;
Integer b = 5;
System.out.println(a == b);
原因:当执行 Integer x = 5 时,Java采用自动装箱功能,实际上编译器执行了Integer.valueOf(5)的操作。这个方法返回一个 Integer 对象,但是在返回之前,先作一个判断,判断当前 i 的值是否在 [-128,127] 区间内,且 IntegerCache 中是否存在此对象,如果存在,则直接返回引用,否则,创建一个新的对象。
public static Integer valueOf (int i)的官方注释如下:
If an new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significant better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 12