zoukankan      html  css  js  c++  java
  • 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() 没有判断商店是否存在,而是判断商店是否有东西

    学习没有一蹴而就,放下急躁,一步一步扎实前进
  • 相关阅读:
    Opencv中cvCopy()和cvCloneImage()的区别(转)
    什么是DC?
    UpdateDate()函数的作用
    宏定义函数指针类型【转】
    将openCV中的IplImage格式的图片显示到Picture控件上
    C程序调用shell脚本共有三种方法
    memset ,memcpy ,memmove,strcpy 的根本区别 与实现
    sizeof strlen length()
    itoa 实现
    string 与 char * 转换
  • 原文地址:https://www.cnblogs.com/jpxjx/p/12166657.html
Copyright © 2011-2022 走看看