字符串在使用 equals 时可能出现空指针错误:在进行字符串比较时,常量写在前面
String name = null;// 比较 name 是否为 "lisi""lisi".equals(name); // 正确写法name.equals("lisi"); // 错误写法
对象数组通过 new 创建出来,却没有初始化,一样会报空指针错误:
// int、boolean等基本类型的数组,在 new 的时候会赋初始值int[] ints = new int[10];for (int anInt : ints) {System.out.println(anInt); // 0}// 对象类型的数组,在 new 的时候不会赋初始值,数组中存放的是 null// 因此,对象数组在通过 new 开辟空间后,还要对数组进行初始化才能正常访问数组中的对象Integer[] nums = new Integer[20];for (Integer num : nums) {System.out.println(num); // null}
List 对象 add null 不报错,但是 addAll 不能添加 null
List<Integer> list = new ArrayList<>(12);list.add(null);List<Integer> nums = null;list.addAll(nums); // addAll() 添加的是集合元素,不允许为 null
