1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java判断list是否为空_java中list集合怎么判断是否为空

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

时间:2023-02-12 18:50:49

相关推荐

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

首先看下面代码

@RequestMapping("/getCatlist")publicString 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 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 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() 没有判断商店是否存在,而是判断商店是否有东西

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。