NullPointerException-----开发中遇到的空指针异常

1.使用CollectionUtils.isEmpty判断空集合

public class TestIsEmpty {
static class Person{}
static class Girl extends Person{} public static void main(String[] args) {
List<Integer> first = new ArrayList<>();
List<Integer> second = null;
List<Person> boy = new ArrayList<>();
boy.add(new Girl());
System.out.println(CollectionUtils.isEmpty(first));//true
System.out.println(CollectionUtils.isEmpty(first));//true
System.out.println(CollectionUtils.isEmpty(first));//false System.out.println(first==null);//false
System.out.println(second==null);//true
System.out.println(boy==null);//false System.out.println(first.size()); //size=0
System.out.println(second.size());// NullPointerException
System.out.println(boy.size()); //size=1 System.out.println(first.isEmpty()); //true
System.out.println(second.isEmpty()); //NullPointerException
System.out.println(boy.isEmpty()); //false 所以:
isEmpty() 或者(list.size() == 0)用于判断List内容是否为空,即表里一个元素也没有
但是使用isEmpty()和size()的前提是,list是一个空集合,而不是null,
所以为了避免异常,建议在使用或赋值list集合之前,做一次空集合创建处理,进行内存空间分配,即: List list2 = new ArrayList()
判断不为空的情况: list!=null && !list.isEmpty()
}
}

二 .容易出现空指针的地方

1.实体类里定义的集合

public class Org {
private Long id;
private String title;
private Long parent;
private List<User> list; public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}
public Long getParent() {return parent;}
public void setParent(Long parent) {this.parent = parent;}
public List<User> getList() {
if(list==null){
list=new ArrayList<>(); //这里最好对这个集合处理一下,防止报空指针
}
return list;
} public void setList(List<User> list) {
this.list = list;
}
}

2.自己定义的集合接收数据库查询的数据

如:List<Org> users=userService.getAll();
如果查询结果为空,users.size=0.users是一个空集合,但不是空
使用前最好判断一下是不是为空
上一篇:Python version 2.7 required, which was not found in the registry


下一篇:并发编程入门(三): 使用C++11实现无锁stack(lock-free stack)