问题

在Java中for循环中防止null的最佳方法是什么?

这看起来很难看:

if (someList != null) {
    for (Object object : someList) {
        // do whatever
    }
}

要么

if (someList == null) {
    return; // Or throw ex
}
for (Object object : someList) {
    // do whatever
}

可能没有任何其他方式。他们应该把它放在for构造本身,如果它是null,那么不要运行循环?


#1 热门回答(202 赞)

你应该更好地验证从哪里获得该列表。

你只需要一个空列表,因为空列表不会失败。

如果你从其他地方得到这个列表并且不知道它是否正常你可以创建一个实用工具方法并像这样使用它:

for( Object o : safe( list ) ) {
   // do whatever 
 }

当然safe将是:

public static List safe( List other ) {
    return other == null ? Collections.EMPTY_LIST : other;
}

#2 热门回答(88 赞)

如果传入null,你可能会编写一个返回空序列的辅助方法:

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

然后使用:

for (Object object : emptyIfNull(someList)) {
}

我不认为我实际上是这样做的 - 我通常会使用你的第二种形式。特别是,"或者抛出ex"很重要 - 如果它真的不应该为null,那么你肯定应该抛出异常。你知道有些东西出了问题,但是你不知道损坏的程度。早点中止。


#3 热门回答(18 赞)

它已经是2017年了,你现在可以使用Apache Commons Collections4

用法:

for(Object obj : ListUtils.emptyIfNull(list1)){
    // Do your stuff
}

你可以使用CollectionUtils.emptyIfNull对其他Collection类执行相同的空值安全检查。


原文链接