CollectionUtils.isEmpty()和CollectionUtils.isNotEmpty()的作用

CollectionUtils.isEmpty()作用:判断参数null或者其size等于0

CollectionUtils.isNotEmpty()作用:判断参数不为null且其size不等于0

添加依赖:

        
            commons-collections
            commons-collections
            3.2.1
        
    

演示判断集合是否为空和判断集合是否不为空的示例:

import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List listA = null;
        List listB = new ArrayList();
        List listC = new ArrayList();
        listC.add(5);
        listC.add(6);
        // 判断集合是否为空
        if (CollectionUtils.isEmpty(listA)) {   // true
            System.out.println("listA为空或size=0");
        }
        if (CollectionUtils.isEmpty(listB)) {   // true
            System.out.println("listB为空或size=0");
        }
        if (CollectionUtils.isEmpty(listC)) {   // false
            System.out.println("listC为空或size=0");
        }

        // 判断集合是否不为空
        if (CollectionUtils.isNotEmpty(listA)) {    // false
            System.out.println("listA不为空且size不等于0");
        }
        if (CollectionUtils.isNotEmpty(listB)) {    // false
            System.out.println("listB不为空且size不等于0");
        }
        if (CollectionUtils.isNotEmpty(listC)) {    // true
            System.out.println("listC不为空且size不等于0");
        }
    }
}

运行结果:

CollectionUtils.isEmpty()和CollectionUtils.isNotEmpty()的作用

演示两种isEmpty区别的示例:

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List listA = null;
        List listB = new ArrayList();
        List listC = new ArrayList();
        listC.add(5);
        listC.add(6);

        // public static boolean isEmpty(Collection coll) (org.apache.commons.collections.CollectionUtils)
        // 和public boolean isEmpty()(java.util.ArrayList;)的区别
        System.out.println(CollectionUtils.isEmpty(listA));
//        System.out.println(listA.isEmpty()); // 打开该行注释程序会报错
        System.out.println(CollectionUtils.isEmpty(listB));
        System.out.println(listB.isEmpty());
        System.out.println(CollectionUtils.isEmpty(listC));
        System.out.println(listC.isEmpty());
    }

}

运行结果:

CollectionUtils.isEmpty()和CollectionUtils.isNotEmpty()的作用

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/7b51debde9.html