代码:
package com.hebi.test;
public class Test {
public static void main(String[] args) {
Integer a1=127;
Integer a2=127;
System.out.println(a1==a2); // true
Integer b1=-128;
Integer b2=-128;
System.out.println(b1==b2); // true
Integer c1=1466;
Integer c2=1466;
System.out.println(c1==c2); // false
Integer d1=-129;
Integer d2=-129;
System.out.println(d1==d2); // false
}
}
结果:
结论:
Integer类型的值,在-128到127之间的数字,用==比较是相等的,超出这个范围的话,用==比较是不相等的
原因:
java中Integer类型对于-128到127之间的数是缓冲区取的,所以用==比较是一致的。
但对于其它的数字是在堆中new出来的。所以地址空间不一样,也就不相等
大佬们的链接: