Java集合优雅的判空/非空

一、乱象

代码中各种同胞写的各种集合判空,很多,很杂乱。大多数是不规范的,而且可能会造成空指针异常。

这篇讲的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);
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值