一、问题
一段代码引发的血案
为了让int类型的方法参数可以接收null值,通常我们会把设置成int类型的包装类型Integer,我们的故事便从这里开始,我们先来看一段代码:
public class Demo {
public static void main(String[] args) {
test(10,10);
test(128,128);
}
public static void test(Integer i,Integer j){
if(i == null || j == null){
return;
}
if(i == j){
System.out.println("成功!");
}else {
System.out.println("失败!");
}
}
}
控制台输出:
成功!
失败!
My God,为什么第2个输出失败,而不是成功!崩溃。。。。
二、原因
猜测
我们猜测是Integer类导致的,我们知道Integer是int类型的包装类,这里就涉及到Java的自动装箱与拆箱了。那什么是自动装箱与拆箱呢?