1.isEmpty() 用于判断List内容是否为空,即list里一个元素也没有,
但是必须在 List list 本身不是空的引用的情况下才行。
即对象本身不能是空对象。
2.null一般判断该List的引用也空的情况下
实战开发项目错误 判断集合为空错误:
一开始我一直用 list !=null 来判断集合里是否有元素,这个是不对 要用isEmpty()判断集合时候有元素,或者用size>0 来判断集合元素个数 集合有元素。
//添加购物车
@PostMapping("/add")
public R<String> add (HttpSession httpSession, @RequestBody ShoppingCart shoppingCart){
Long userId = (Long) httpSession.getAttribute("user"); //拿到用户id
shoppingCart.setUserId(userId);
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
String name = shoppingCart.getName(); //拿到名字
queryWrapper.eq(ShoppingCart::getName,name);
List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
//判断改菜是否已经添加过
if(list.size()>0){ //不能用 list!=null null 是判断list的引用也为空 就是list没有开辟空间
// 现在集合里没有内容 但是开辟空间里 用 null 判断也是为true
shoppingCartService.remove(queryWrapper); //先删除 在添加
for (ShoppingCart l:list
) {
l.setNumber(l.getNumber()+1); // 数量加1
}
shoppingCartService.saveBatch(list); // 添加到数据库
return R.success("添加成功");
}
shoppingCartService.save(shoppingCart); //如果没有添加就 添加菜品
return R.success("添加购车成功");
}
报空指针异常
List<String> list=null;
if(!list.isEmpty()) {
System.out.println(1);
}else{
System.out.println(2);
}
结果:
Exception in thread “main” java.lang.NullPointerException
改为:
List<String> list=null;
if(list!=null && !list.isEmpty()) {
System.out.println(1);
}else{
System.out.println(2);
}
结果:2
_____________________________________________________________________________
1.isEmpty() 用于判断List内容是否为空,即list里一个元素也没有,
但是必须在 List list 本身不是空的引用的情况下才行。
即对象本身不能是空对象。
2.null一般判断该List的引用也空的情况下
例如: List list1 =null;
List list2=new ArrayList();
System.out.println(list2.isEmpty()); //true
System.out.println(list1.isEmpty()); //空指针异常
因为list2对象已经分配了空间,所以可以使用list2.isEmpty()来判断使用有元素
如果用list2 !=null来判断,只能判断list2是否分配了空间
例如上面的list1使用list1.isEmpty())就会报空指针异常
list2.isEmpty()就为true
如果将上面的判断修改为
System.out.println(list2.isEmpty());
System.out.println(list1 == null);
两者就都为true了。