在Java中防止for循环为空的最好方法是什么?

这看起来很丑陋:

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

Or

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

可能没有别的办法了。他们是否应该把它放在for构造本身中,如果它是null,那么就不运行循环?


当前回答

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

的用法:

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

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

其他回答

Java 8可选:

for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
    // do whatever
}

使用,CollectionUtils。方法isEmpty(集合coll),该方法是空安全检查指定的集合是否为空。

对于此导入org.apache.commons.collections.CollectionUtils。

Maven的依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.0</version>
</dependency>

另一种有效防止for循环中出现null值的方法是使用谷歌Guava的Optional<T>包装集合,因为这样可以明确有效空集合的可能性,因为客户端将期望使用Optional. ispresent()检查集合是否存在。

for (Object object : someList) {

   // do whatever
}  throws the null pointer exception.

我已经修改了上面的答案,所以你不需要从对象强制转换

public static <T> List<T> safeClient( List<T> other ) {
            return other == null ? Collections.EMPTY_LIST : other;
}

然后简单地调用列表

for (MyOwnObject ownObject : safeClient(someList)) {
    // do whatever
}

解释: MyOwnObject:如果List<Integer>,那么MyOwnObject在这种情况下将是Integer。