在实践的项目开发中,我们经常能够碰到用list或者set等结构进行数据存储,但是这些数据结构使用之前必须要判断该结构是否是null或者是empty,否则严重的会有NullPointerException。那我们就看看实际开发中怎样处理这种集合类型吧。
方法/步骤
-
首先看下我们通常的list的用法:
List<String>list=new ArrayList<String>();
list=xxxService.selectInfoByXXX();//此处返回一个list
for(String str :list){
System.out.println(str);
}
上面的用法有什么问题?
如果list在调用xxxService.selectInfoByXXX()返回null的话,那么在for循环第一行就会抛出空指针异常!
-
正常情况我们会怎样处理呢?
就是在for循环外面加一个if判断,如下所示
List<String>list=new ArrayList<String>();
list=xxxService.selectInfoByXXX();//此处返回一个list
if(list!=null&&list.size()>0)
{
for(String str :list){
System.out.println(str);
}
}
注意,if判断必须先判断!=null不然仍然会抛空指针的!
-
再给大家分享一种更好的方式:
List<String>list=new ArrayList<String>();
list=xxxService.selectInfoByXXX();//此处返回一个list
if(CollectionUtils.isNotEmpty(list))
{
for(String str :list){
System.out.println(str);
}
}
这种实现方式代码可读性更好、更简洁也更好维护。
CollectionUtils.isNotEmpty(list)是apache-common中封装的方法。
源码如下:
public static boolean isNotEmpty(Collection coll) { return !CollectionUtils.isEmpty(coll); }
public static boolean isEmpty(Collection coll) { return (coll == null || coll.isEmpty()); }
其实就是和步骤的if一样的效果!