首先看下面代碼
@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() 沒有判斷商店是否存在,而是判斷商店是否有東西