Null check in an enhanced for loop

前端 未结 11 1934
南旧
南旧 2020-11-29 15:35

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

This seems ugly :

if (someList != null) {
    for (Object object : someList) {
            


        
相关标签:
11条回答
  • 2020-11-29 16:27

    Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.

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

    Maven dependency

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.0</version>
    </dependency>
    
    0 讨论(0)
  • 2020-11-29 16:29

    You could potentially write a helper method which returned an empty sequence if you passed in 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 something has gone wrong, but you don't know the extent of the damage. Abort early.

    0 讨论(0)
  • 2020-11-29 16:31
    for (Object object : someList) {
    
       // do whatever
    }  throws the null pointer exception.
    
    0 讨论(0)
  • 2020-11-29 16:35

    I have modified the above answer, so you don't need to cast from 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.

    0 讨论(0)
  • 2020-11-29 16:38

    With Java 8 Optional:

    for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
        // do whatever
    }
    
    0 讨论(0)
提交回复
热议问题