Python 官方文档:入门教程 => 点击学习
目录collection中的null,isEmpty用法第一种情况第二种情况第三种情况CollectionUtils.isEmpty和 == null的区别本文所指的 Collect
只使用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
只创建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异常
org.apache.commons.collections
CollectionUtils.isEmpty() 包含null,size=0等多种情况
而== null 只能用来判断是否为null
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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: java-collection中的null,isEmpty用法
本文链接: https://www.lsjlt.com/news/140693.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0