做过开发的人应该都知道下面程序运行的结果
@Data
@NoArgsConstructor
public class Person {
private String name;
private Integer age;
}
public class NullTest {
public static void main(String[] args) {
Person person = new Person();
String name = person.getName();
// name.equals(""); // 空指针
"".equals(name); // nothing
}
}
但是你知道下面程序的运行结果吗
public class NullTest {
public static void main(String[] args) {
Person person = new Person();
Integer age = person.getAge();
int a = 1;
System.out.println(age == a); // 空指针
System.out.println(a == age); // 空指针
}
}
没错,无论age在左边还是右边,都会报空指针,因为在将Integer和int进行比较的时候,都会先进行拆箱操作,而对null拆箱总是会抛出NullPointerException
那遇到这种情况怎么解决呢?
public class NullTest {
public static void main(String[] args) {
Person person = new Person();
Integer age = person.getAge();
int a = 1;
if (!Objects.isNull(age)) {
System.out.println(age == a);
}
}
}