一、乱象
代码中各种同胞写的各种集合判空,很多,很杂乱。大多数是不规范的,而且可能会造成空指针异常。
这篇讲的CollectionUtils工具类是在apache下的, 而不是springframework下的CollectionUtils。
个人觉得CollectionUtils在真实项目中,可以使你的代码更加简洁和安全。
所以需要倒入相关jar包,目前从maven找到最新jar包如下:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.3</version>
</dependency>
一、API常用方法
/**
* 6、空安全检查指定的集合是否为空
*/
CollectionUtils.isEmpty(Collection<?> coll)
/**
* 7、 空安全检查指定的集合是否为空。
*/
CollectionUtils.isNotEmpty(Collection<?> coll)
它使得集合判空代码非常简洁,我们可以避免写如下繁长的代码:
if(null != list && !list.isEmpty()){
...
}
二、集合判空的源码
/**
* Null-safe check if the specified collection is empty.
* <p>
* Null returns true.
*
* @param coll the collection to check, may be null
* @return true if empty or null
* @since Commons Collections 3.2
*/
public static boolean isEmpty(Collection coll) {
return (coll == null || coll.isEmpty());
}
/**
* Null-safe check if the specified collection is not empty.
* <p>
* Null returns false.
*
* @param coll the collection to check, may be null
* @return true if non-null and non-empty
* @since Commons Collections 3.2
*/
public static boolean isNotEmpty(Collection coll) {
return !CollectionUtils.isEmpty(coll);
}