小徐带你避坑List判断非空时的操作

list 集合遍历时遇到的坑

对于List进行非空判断的时候,对于新手来说可能会遇到的问题:

错误的例子

 List<CpuBuyofferProgressEntity> cpuBuyofferProgressEntityList = ipuQuotation.getProgressEntityList();
   if (cpuBuyofferProgressEntityList.size() > 0 && cpuBuyofferProgressEntityList != null){
                    for (CpuBuyofferProgressEntity cpuBuyofferProgressEntity : cpuBuyofferProgressEntityList){
                        if (cpuBuyofferProgressEntity.getProcessType().equals("36")){
                            ids2.add(Long.valueOf(cpuBuyofferProgressEntity.getTargetId()));
                        }
                    }
                }

这时运行会报空指针异常,
错误解读:

List<CpuBuyofferProgressEntity> cpuBuyofferProgressEntityList = ipuQuotation.getProgressEntityList();

这个意思是如果ipuQuotation.getProgressEntityList()取不到数据,
也就是说 cpuBuyofferProgressEntityList == null 或者说 list没有被初始化(new ArrayList())
直接先进行cpuBuyofferProgressEntityList.size() > 0的判断 会报空指针的错误

list正确的判断非空的操作如下 切记哟!!!

 List<CpuBuyofferProgressEntity> cpuBuyofferProgressEntityList = ipuQuotation.getProgressEntityList();
   if (cpuBuyofferProgressEntityList != null && cpuBuyofferProgressEntityList.size() > 0){
                    for (CpuBuyofferProgressEntity cpuBuyofferProgressEntity : cpuBuyofferProgressEntityList){
                        if (cpuBuyofferProgressEntity.getProcessType().equals("36")){
                            ids2.add(Long.valueOf(cpuBuyofferProgressEntity.getTargetId()));
                        }
                    }
                }

解读:先判断list 是否被初始化即(new ArrayList()) 再判断是否有数据

你可能感兴趣的:(java基础,javaWeb,面试,java)