Integer存在一个缓存机制,如果是在-128~127之间,会直接比较其值,但是超过范围后就会比较内存地址.
public class IntegerTest {
public static void main(String[] args) {
Integer i1 = new Integer(3306);
Integer i2 = new Integer(127);
Integer i3 = new Integer(3306);
Integer i4 = new Integer(127);
System.out.println(i1.valueOf(3306));
System.out.println(i3.valueOf(3306));
System.out.println(i1.valueOf(3306) == i3.valueOf(3306));
System.out.println(i2.valueOf(127));
System.out.println(i4.valueOf(127));
System.out.println(i2.valueOf(127) == i4.valueOf(127));
}
}
从上图结果我们可以看出,虽然数值输出的相同,但是在比较过程中,在超出-128~127范围比较是不相等的.
- 在Integer的valueOf()方法中,当数值在 -128-127 之间时,数值都存储在一个cache数组中,该数组相当于一个缓存,当我们在-128-127之间进行自动装箱的时候,我们就直接 返回该值在内存当中的地址,所以在-128~127之间的数值用==进行比较是相等的,因为判断的都是同一个对象的地址,但如果不在这个区间的数,则需要新开辟一个内存空间,比较的就不是同一个对象,所以不相等.