嗷嗷踩坑,平时拆箱装箱概念说得清,一到用时忘干净
背景
要做一个对象中的Ingeter类型属性的值与1或者0的比较,写成了如下的样子,报了空指针异常:Exception in thread "main" java.lang.NullPointerException
public class DictType {
private Integer type;
}
public static void main(String[] args) {
DictType dictType = new DictType();
dictType.setType(null);
System.out.println(1== dictType.getType());
}
原因
究其原因是我及进行了int类型的值,与Integer类型的值的比较。
那在Integer和int进行比较是,会对Integer类型的值进行自动拆箱,自动拆箱就是调用了Integer的intValue()的方法,由于我写的例子中,Integer类型的值为null,这时候调用intValue()方法,就会报NullPointerException。
解决办法
所以,在包装类和基本数据类型进行比较的时候要判断包装类是否为null啊!!!!!!