好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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测试数据mons.collections.CollectionUtils;

?

1

CollectionUtils.isEmpty(Collecions<extend>);

可以避免

java.lang.NullPointerException异常

CollectionUtils.isEmpty和 == null的区别

本文所指的 CollectionUtils 所属包

?

1

org.apache测试数据mons.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

查看更多关于java-collection中的null,isEmpty用法的详细内容...

  阅读:43次