简体   繁体   English

增强的 for 循环中的空检查

[英]Null check in an enhanced for loop

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 for construct itself, if it is null then don't run the loop?他们是否应该将它放在for构造本身中,如果它为 null 则不要运行循环?

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 safe would be:当然safe是:

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

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.特别是,“or throw ex”很重要——如果它真的不应该为空,你绝对应该抛出一个异常。 You know that something has gone wrong, but you don't know the extent of the damage.你知道了问题,但你不知道损害的程度。 Abort early.早点放弃。

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对其他 Collection 类执行相同的空安全检查。

With Java 8 Optional :使用 Java 8 Optional

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

Use ArrayUtils.nullToEmpty from the commons-lang library for Arrayscommons-lang库中的ArrayUtils.nullToEmpty用于数组

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

This functionality exists in the commons-lang library, 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 DRY mantra, I believe it is worth noting.这与@OscarRyz 给出的答案相同,但为了DRY口头禅,我认为值得注意。 See the commons-lang project page.请参阅commons-lang项目页面。 Here is the nullToEmpty API documentation and source这是nullToEmpty API 文档源代码

Maven entry to include commons-lang in your project if it is not already. Maven 条目以在您的项目中包含commons-lang (如果尚未包含)。

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

Unfortunately, commons-lang doesn't provide this functionality for List types.不幸的是, commons-lang没有为List类型提供这个功能。 In this case you would have to use a helper method as previously mentioned.在这种情况下,您将不得不使用前面提到的辅助方法。

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

If you are getting that List from 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 null check.如果您无法更改实现,那么您将陷入null检查。 If it should't be null , then throw an exception.如果它不应该是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.我不会选择返回空列表的辅助方法,因为它有时可能很有用,但随后您会习惯于在可能隐藏一些错误的每个循环中调用它。

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。

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

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) .对于任何对编写自己的静态空安全方法不感兴趣的人,您可以使用:commons-lang 的org.apache.commons.lang.ObjectUtils.defaultIfNull(Object, Object) For example:例如:

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

ObjectUtils.defaultIfNull JavaDoc ObjectUtils.defaultIfNull JavaDoc

Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.使用CollectionUtils.isEmpty(Collection coll)方法,该方法是空安全的,检查指定的集合是否为空。

for this import org.apache.commons.collections.CollectionUtils .为此import org.apache.commons.collections.CollectionUtils

Maven dependency Maven 依赖

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

The "||" “||” or the "??"或者 ”??” comes in handy here在这里派上用场

Best choice and IE compatible is the ||最佳选择和 IE 兼容是 ||

for (Object object : someList || []) {
    // undefined and null gets defaulted to an empty array []
}

Nullish coalescing operator : Not IE compatible 空合并运算符与 IE 不兼容

for (Object object : someList ?? []) {
    // undefined and null gets defaulted to an empty array []
}
for (Object object : someList) {

   // do whatever
}  throws the null pointer exception.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM