java中list集合怎么判断是否为空

2022-12-09,,,,

首先看下面代码

@RequestMapping("/getCatlist")
public String getCatlist(HttpSession session,HttpServletRequest request) {
String pcategoryIdStr = request.getParameter("pcategoryIdStr");
if (pcategoryIdStr != null && !pcategoryIdStr .equals("")) {
System.out.println("===="+pcategoryIdStr);
Long pcategoryId = Long.parseLong(pcategoryIdStr);
List<Product> catlist = productService.getCatlist(pcategoryId);
if (catlist==null || catlist.equals("")) {
catlist = productService.getChildrenCatlist(pcategoryId);
for (Product product : catlist) {
System.out.println(product);
}
session.setAttribute("catlist", catlist);
}
session.setAttribute("catlist", catlist);
}
return "catlist";
}

咋一看似乎没错。然而跑起来,一直不执行红色代码if语句下的代码。

仔细看代码 ,此处需要判断是否为空的是list集合,如果不是集合,那么这么写代码是没错的,但是java中判断list集合是否为空却不能这样写代码

需要改为:

List<Product> catlist = productService.getCatlist(pcategoryId);
if (catlist==null || catlist.isEmpty()) {
catlist = productService.getChildrenCatlist(pcategoryId);
for (Product product : catlist) {
System.out.println(product);
}
session.setAttribute("catlist", catlist);
}

总结:

问题:list集合如何判空

方法一:

if(null == list || list.size() ==0 ){

  //为空的情况
}else{   //不为空的情况
}

方法二:

if(list!=null && !list.isEmpty()){
   //不为空的情况
}else{
   //为空的情况
}

问题1:list.isEmpty() 和 list.size()==0 有啥区别呢?
  答案:没有区别 。isEmpty()判断有没有元素,而size()返回有几个元素, 如果判断一个集合有无元素 建议用isEmpty()方法.比较符合逻辑用法。

问题2:list!=null 跟 ! list.isEmpty()有什么区别?

  这就相当与,你要要到商店买东西

    list!=null 首先判断是否有商店

    !list.isEmpty() 没有判断商店是否存在,而是判断商店是否有东西

java中list集合怎么判断是否为空的相关教程结束。

《java中list集合怎么判断是否为空.doc》

下载本文的Word格式文档,以方便收藏与打印。