This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021
Lists are often manipulated in real development, and null-nulling is often required to avoid null-pointer exceptions. The general way to write this is:
if(the list! =null && list.size>0) {// Perform the set operation
}
Copy the code
Method 1 (large amount of data, low efficiency) :if(list! =null && list.size()>0Method 2 (large amount of data, high efficiency) :if(list! =null && !list.isEmpty()){
}
Copy the code
Look at the ArrayList source code below, don’t understand why the efficiency gap (just remember that for now, unfortunately).
public int size(a) {
return size;
}
public boolean isEmpty(a) {
return size == 0;
}
Copy the code
Most frameworks provide a utility class like CollectionUtils
- For example, the Spring framework:
The package path is as follows:
package org.springframework.util.CollectionUtils;
Copy the code
With utility classes, collection nulling is much simpler:
if(CollectionUtils.isEmpty()){
// The operation on the set
}
Copy the code
- Another example is the Apache CollectionUtils utility class:
Maven coordinates:
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.22.</version>
</dependency>
Copy the code
Package path:
package org.apache.commons.collections;
Copy the code
With utility classes, collection nulling is much simpler:
if(CollectionUtils.isEmpty()){
// The operation on the set} orif(CollectionUtils.isNotEmpty()){
// The operation on the set
}
Copy the code
Reference links: blog.csdn.net/z1573262158…