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

首先看下面代码

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

posted @   城为唯一  阅读(11715)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示