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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值