Java 增强的 for 循环中的空检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2250031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:14:21  来源:igfitidea点击:

Null check in an enhanced for loop

javasyntaxloopsfor-loop

提问by fastcodejava

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

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

This seems ugly :

这看起来很难看:

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

Or

或者

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

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

可能没有其他办法了。他们是否应该将它放在for构造本身中,如果它为空,则不要运行循环?

采纳答案by OscarRyz

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 
 }

And of course safewould be:

当然safe是:

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

回答by Jon Skeet

You could potentially write a helper method which returned an empty sequence if you passed in null:

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

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

Then use:

然后使用:

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

I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that somethinghas gone wrong, but you don't know the extent of the damage. Abort early.

我不认为我真的会这样做 - 我通常会使用你的第二种形式。特别是,“or throw ex”很重要——如果它真的不应该为空,你绝对应该抛出一个异常。你知道了问题,但你不知道损害的程度。早点放弃。

回答by Lombo

If you are getting that Listfrom a method call that you implement, then don't return null, return an empty List.

如果你是List从你实现的方法调用中得到的,那么不要返回null,返回一个空的List

If you can't change the implementation then you are stuck with the nullcheck. If it should't be null, then throw an exception.

如果你不能改变实现,那么你就会被null检查卡住。如果不应该null,则抛出异常。

I would not go for the helper method that returns an empty list because it may be useful some times but then you would get used to call it in every loop you make possibly hiding some bugs.

我不会选择返回空列表的辅助方法,因为它有时可能很有用,但随后您会习惯于在可能隐藏一些错误的每个循环中调用它。

回答by Nico de Wet

Another way to effectively guard against a null in a for loop is to wrap your collection with Google Guava's Optional<T>as this, one hopes, makes the possibility of an effectively empty collection clear since the client would be expected to check if the collection is present with Optional.isPresent().

在 for 循环中有效防止 null 的另一种方法是用 Google Guava 包装您的集合,Optional<T>因为人们希望这样可以使有效空集合的可能性变得清晰,因为客户端需要检查集合是否存在Optional.isPresent().

回答by Haris Iltifat

I have modified the above answer, so you don't need to cast from Object

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

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

and then simply call the List by

然后简单地调用列表

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

Explaination: MyOwnObject: If List<Integer>then MyOwnObject will be Integer in this case.

说明: MyOwnObject:如果List<Integer>在这种情况下 MyOwnObject 将是 Integer。

回答by user6315386

for (Object object : someList) {

   // do whatever
}  throws the null pointer exception.

回答by sdc

Use ArrayUtils.nullToEmptyfrom the commons-langlibrary for Arrays

使用ArrayUtils.nullToEmpty来自commons-lang于阵列库

for( Object o : ArrayUtils.nullToEmpty(list) ) {
   // do whatever 
}

This functionality exists in the commons-langlibrary, which is included in most Java projects.

此功能存在于commons-lang库中,该库包含在大多数 Java 项目中。

// ArrayUtils.nullToEmpty source code 
public static Object[] nullToEmpty(final Object[] array) {
    if (isEmpty(array)) {
        return EMPTY_OBJECT_ARRAY;
    }
    return array;
}

// ArrayUtils.isEmpty source code
public static boolean isEmpty(final Object[] array) {
    return array == null || array.length == 0;
}

This is the same as the answer given by @OscarRyz, but for the sake of the DRYmantra, I believe it is worth noting. See the commons-langproject page. Here is the nullToEmptyAPI documentationand source

这与@OscarRyz 给出的答案相同,但为了DRY口头禅,我认为值得注意。请参阅commons-lang项目页面。这是nullToEmptyAPI文档来源

Maven entry to include commons-langin your project if it is not already.

要包含commons-lang在您的项目中的Maven 条目(如果尚未包含)。

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Unfortunately, commons-langdoesn't provide this functionality for Listtypes. In this case you would have to use a helper method as previously mentioned.

不幸的是,commons-lang没有为List类型提供此功能。在这种情况下,您将不得不使用前面提到的辅助方法。

public static <E> List<E> nullToEmpty(List<E> list)
{
    if(list == null || list.isEmpty())
    {
        return Collections.emptyList();
    }
    return list;
}

回答by Jacob Briscoe

For anyone uninterested in writing their own static null safety method you can use: commons-lang's org.apache.commons.lang.ObjectUtils.defaultIfNull(Object, Object). For example:

对于任何对编写自己的静态空安全方法不感兴趣的人,您可以使用:commons-lang's org.apache.commons.lang.ObjectUtils.defaultIfNull(Object, Object). 例如:

    for (final String item : 
    (List<String>)ObjectUtils.defaultIfNull(items, Collections.emptyList())) { ... }

ObjectUtils.defaultIfNull JavaDoc

ObjectUtils.defaultIfNull JavaDoc

回答by Fred Pym

It's already 2017, and you can now use Apache Commons Collections4

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

The usage:

用法:

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

You can do the same null-safe check to other Collection classes with CollectionUtils.emptyIfNull.

您可以使用CollectionUtils.emptyIfNull.

回答by holmis83

With Java 8 Optional:

使用 Java 8 Optional

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