public static void main(String[] args) {
Integer a = null;
System.out.println(1 == a);
System.out.println(a == 1);
}
这段代码第一次打印就会报错,是因为integer类型会自动拆箱。
正确方法应该是
public static void main(String[] args) {
Integer a = null;
System.out.println(Integer.valueOf(1).equals(a));
}
在integer的值在-128~127之间的时候是可以使用==号来比较。但是当值大于127或者为null的时候是非常容易出问题的。所以为了避免这种低级错,所有的integer比较都要用equals,尽管你可能明确知道他是不会出错的。
public static void main(String[] args) {
Integer a = new Integer(128);
Integer b = new Integer(128);
Integer c = new Integer(127);
Integer d = new Integer(127);
System.out.println(b==a);//false
System.out.println(d==c);//false
}
public static void main(String[] args) {
Integer a = 128;
Integer b = 128;
Integer c = 127;
Integer d = 127;
System.out.println(b==a);//false
System.out.println(d==c);//true
}