NPE(NullPointerException)
方法的返回值可以为null,不强制返回空集合,或者空对象等,必须添加注释充分说明什么情况下会返回 null 值。防止NPE是调用者的责任:返回空集合或空对象仍然可能在“远程调用失败、序列化失败、运行时异常”时返回null防止NPE:包装类为null,集合元素为null,级联调用,数据库查询结果,远程调用返回对象,session中对象来自阿里巴巴java开发手册泰山版 创建数组对象,元素为null
public class BucketSort {
private static class Node {
private int key;
private int next;
public Node() {
}
public Node(int key, int next) {
this.key = key;
this.next = next;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
}
public static void main(String[] args) {
// 创建数组对象,只是分配了空间
Node[] nodes = new Node[n];
for (int i = 0; i < n; i++) {
// 抛出 NPE
nodes[i].key = r[i];
nodes[i].next = i + 1;
}
}
}
包装类为null,自动拆箱报错
private static int testIntegerNull() {
Integer integer = null;
return integer;
}
public static void main(String[] args) {
testIntegerNull();
}
集合元素为null
private static void testCollectionElementNull() {
String str = null;
List list = new ArrayList<>();
list.add(str);
if (!list.isEmpty()) {
System.out.println(list.get(0).equals("xcrj"));
}
}
public static void main(String[] args) {
testCollectionElementNull();
}
对象级联调用
// 建议使用Optional处理 obj.getA().getB().getC()



