Java: List empty sentenced conditions: List = null and List.size = 0

When you need to carry out a sentence LIst air operations we can use the following two statements:

if (list == null || list.size() == 0) {}

if (list != null && list.size() != 0) {}

Some may doubt if they meet   list == null, then this list is not to empty it? Why then use another condition  list.size == 0 it?

 

First, we need to understand two conditions represent what meanings:

1.    list == null: determining a list has not been initialized, i.e. whether the list is assigned is null, as  List list = null;, satisfies this condition, then the list is no data

2.   list.size == 0: used for determining whether there is data in the list, the list satisfies this condition is no data

 

If only  list == null: Once the list is initialized  List list2 = new ArrayList (); , this time is no longer null list, but the list is not data. If only  list == null to determine whether it is empty, it will be an error of judgment.

If only  list .size == 0: If the list is not initialized, null pointer error will be reported when using this condition, you can not reach sentenced empty goal. Therefore, when the use conditions, must be determined whether the initialization list


 

 

to sum up:

When the List were sentenced empty, it requires two conditions: first use  list == null to determine whether the list after initialization, re-use  if the list .size == 0 judgment is empty.

Reference link: https: //www.cnblogs.com/huiAlex/p/8594270.html

Guess you like

Origin www.cnblogs.com/wmxblog/p/10972211.html