增强的 for 循环中的空检查 [英] Null check in an enhanced for loop

查看:28
本文介绍了增强的 for 循环中的空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to guard against null in a for loop in Java?

这看起来很丑:

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

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

可能没有任何其他方式.他们是否应该将它放在 for 构造本身中,如果它为 null 则不运行循环?

There might not be any other way. Should they have put it in the for construct itself, if it is null then don't run the loop?

推荐答案

您应该更好地验证您从何处获得该列表.

You should better verify where you get that list from.

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

An empty list is all you need, because an empty list won't fail.

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

If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:

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

当然 safe 将是:

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

这篇关于增强的 for 循环中的空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆