public static void main(String[] args) {
printEachList(1);
printEachList(2);
printEachList(3);
printEachList(4);
standardPrintStyle();
}
//标准写法
private static void standardPrintStyle() {
int key = 2;
List<Long> list = getList(2);
if (null != list) {//只需要判断null,size=0时不会执行for循环
for (Long temp : list) {
if (null == temp) {//temp可能为null,表示list元素指向的对象为null对象,但是元素的值(null对象的引用)不为空
System.out.println("遇到对象为null,跳过");
continue;
}
System.out.println(String.format("key_%d:%s", key, temp.toString()));
}
}
}
private static void printEachList(int key) {
List<Long> list = getList(key);
try {
for (Long temp : list) {
System.out.println(String.format("key_%d:%s", key, temp.toString()));
}
} catch (Exception e) {
System.out.println("list是否为null --》" + CollectionUtils.isEmpty(list));
System.out.println(String.format("key_%d error:%s", key, e));
}
}
private static List<Long> getList(int key) {
List<Long> list = null;
switch (key) {
case 1:
list = new ArrayList<Long>();
list.add(1L);
list.add(2L);
break;
case 2:
list = new ArrayList<Long>();
list.add(null);
list.add(1L);
break;
case 3:
list = new ArrayList<Long>();
break;
default:
break;
}
return list;
}
执行结果:
key_1:1
key_1:2
list是否为null --》false
key_2 error:java.lang.NullPointerException
list是否为null --》true
key_4 error:java.lang.NullPointerException
遇到对象为null,跳过
key_2:1
if(list!=null && !list.isEmpty()){
//在这个里操作list
}else{
//做其他处理
}
原文:https://www.cnblogs.com/east7/p/11140889.html