The difference between isEmpty and null

List<对象> list = new List<对象>;
//代表有内容
if(!list.isEmpty){
    ...
}
报错:java.lang.NullPointerException //空指针异常
if(list.isEmpty != null){
    ...
}
可以正常运行

What is the difference between isEmpt and null?
isEmpty() is used to judge whether the content of the List is empty, only when the list itself is not an empty reference;
null is used to judge whether there is this collection object;

In general, null and isEmpty will be used in combination

//这里先判断有没有这个集合再判断这个集合里有没有对象.顺序不能反;
if(list != null && !list.isEmpty()){
    ...
}

It's good to learn from others' examples, and I hope to share here to help you understand:
For example, I have an empty water glass (list), and you don't have it, then you are null, and my size is 0. If you want to fill water, you need to buy a water cup yourself (new ArrayList();), but I can fill it directly (list.add(water)). If you pour water directly without a cup, the water will flow out (null pointer exception).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643907&siteId=291194637