服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java-collection中的null,isEmpty用法

java-collection中的null,isEmpty用法

2022-08-05 12:08黄国攀 Java教程

这篇文章主要介绍了java-collection中的null,isEmpty用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

collection中的null,isEmpty用法

只使用java utils包的isEmpty.

第一种情况

实例化list,但是size为空。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
    List<String> list =new ArrayList<>();
        if (list.isEmpty()) {
            System.out.println("1");
        }
        if (!list.isEmpty()) {
            System.out.println("2");
        }
        if (list != null) {
            System.out.println("3");
        }
                if (list != null && list.size() > 0) {
                        System.out.println("4");
                }

输出:

1

3

第二种情况

add值到list中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
        List<String> list =new ArrayList<>();
        list.add("da");
        if (list.isEmpty()) {
            System.out.println("1");
        }
        if (!list.isEmpty()) {
            System.out.println("2");
        }
        if (list == null) {
            System.out.println("3");
        }
                if (list != null && list.size() > 0) {
                        System.out.println("4");
                }

输出:

2

4

第三种情况

只创建list的引用,不实例化。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
List<String> list = null;
        if (list.isEmpty()) {
            System.out.println("1");
        }
        if (!list.isEmpty()) {
            System.out.println("2");
        }
        if (list != null) {
            System.out.println("3");
        }
        if (list != null && list.size() > 0) {
            System.out.println("4");
        }

输出:

Exception in thread "main" java.lang.NullPointerException 

改进办法:

使用org.apache.commons.collections.CollectionUtils;

?
1
CollectionUtils.isEmpty(Collecions<extend>);

可以避免

java.lang.NullPointerException异常

CollectionUtils.isEmpty和 == null的区别

本文所指的 CollectionUtils 所属包

?
1
org.apache.commons.collections

CollectionUtils.isEmpty() 包含null,size=0等多种情况

而== null 只能用来判断是否为null

举个例子

?
1
2
3
4
5
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("[创建订单]购物车不能为空,customerOrderForm = {}", customerOrderForm);
            throw new CustomerOrderControllerException(CustomerOrderControllerStateEnum.SHOPPING_CART_EMPTY);
        }
        OrderDTO orderDTOResult = orderService.createOrder(orderDTO);

此处if判断条件中,不仅可以判断获取的List是否为null,还能判断获取的List的size是否为0

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u010857795/article/details/50731311

延伸 · 阅读

精彩推荐