需要注意使用**isEmpty**可能会出现空指针异常情况,推荐使用CollectionUtils.isEmpty

  1. public static void main(String[] args) {
  2. /*----------------【Start】isEmpty方法检查-----------------*/
  3. List<String> strList1 = Lists.newArrayList();
  4. System.out.println(CollectionUtils.isEmpty(strList1));//true
  5. System.out.println(CollectionUtils.isEmpty(new ArrayList()));//true
  6. System.out.println(strList1 == null);//false
  7. System.out.println(strList1.size());//0
  8. List<String> strList2 = new ArrayList<>();
  9. System.out.println(strList2 == null);//false
  10. strList2 = null;
  11. System.out.println(strList2 == null);//true
  12. System.out.println(CollectionUtils.isEmpty(strList2));//true
  13. /*----------------【END】isEmpty方法检查-----------------*/
  14. List<String> strList3 = Lists.newArrayList();
  15. List<String> strings = new ArrayList<>();
  16. System.out.println("strList3 = " + strList3.isEmpty());//true
  17. System.out.println("strings.isEmpty() = " + strings.isEmpty());//true
  18. strings = null;
  19. System.out.println("strings.isEmpty() null = " + strings.isEmpty());//空指针异常
  20. }

isEmpty对集合校验null - 图1

总结

1:刚创建出来的List长度为0,但不为null

2:CollectionUtils.isEmpty()方法可以检查null和长度为0的list