java-collection中的null,isEmpty用法
collection中的null,isEmpty用法
只使用java utils包的isEmpty.
第一種情況
實例化list,但是size為空。
?? ?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中
?? ??? ?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
第三種情況
只創(chuàng)建list的引用,不實例化。
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;
CollectionUtils.isEmpty(Collecions<extend>);
可以避免
java.lang.NullPointerException異常
CollectionUtils.isEmpty和 == null的區(qū)別
本文所指的 CollectionUtils 所屬包
org.apache.commons.collections
CollectionUtils.isEmpty() 包含null,size=0等多種情況
而== null 只能用來判斷是否為null
舉個例子
? ? ? ? if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) { ? ? ? ? ? ? log.error("[創(chuàng)建訂單]購物車不能為空,customerOrderForm = {}", customerOrderForm); ? ? ? ? ? ? throw new CustomerOrderControllerException(CustomerOrderControllerStateEnum.SHOPPING_CART_EMPTY); ? ? ? ? } ? ? ? ? OrderDTO orderDTOResult = orderService.createOrder(orderDTO);
此處if判斷條件中,不僅可以判斷獲取的List是否為null,還能判斷獲取的List的size是否為0
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java數(shù)據(jù)庫連接池新手入門一篇就夠了,太簡單了!
數(shù)據(jù)庫連接池負責分配、管理和釋放數(shù)據(jù)庫連接,釋放空閑時間超過最大空閑時間的數(shù)據(jù)庫連接來避免因為沒有釋放數(shù)據(jù)庫連接而引起的數(shù)據(jù)庫連接遺漏,這項技術能明顯提高對數(shù)據(jù)庫操作的性能2021-06-06Java中ArrayList去除重復元素(包括字符串和自定義對象)
本文主要介紹了Java中ArrayList去除重復元素(包括字符串和自定義對象)的方法。具有很好的參考價值。下面跟著小編一起來看下吧2017-03-03AsyncHttpClient ListenableFuture源碼流程解讀
這篇文章主要為大家介紹了AsyncHttpClient ListenableFuture源碼流程解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12淺析 ArrayList 和 LinkedList 有什么區(qū)別
ArrayList 和 LinkedList 有什么區(qū)別,是面試官非常喜歡問的一個問題。今天通過本文給大家詳細介紹下,感興趣的朋友跟隨小編一起看看吧2020-10-10