StephanM
StephanM

Reputation: 1400

Enhanced for loop and null check of objects

lets say i have the following code:

for (AnyObject anyObject : anyObjectList) {
    System.out.println(anyObject.doSomething());
}

My question is: I read that its possible to add null to at least some kind of list types. If im right: shouldn't be there always a null check before you access the method of the iterated class? Im just asking because i have never seen so far a enhanced for loop with a null check like this for example:

for (AnyObject anyObject : anyObjectList) {
    if (anyObject != null) {
        System.out.println(anyObject.doSomething());
    }
}

Upvotes: 2

Views: 4843

Answers (3)

shijin
shijin

Reputation: 3046

for (AnyObject anyObject : anyObjectList) {
    if (anyObject != null) {
        System.out.println(anyObject.doSomething());
    } else {
        /* something went wrong -- report error, debugging info, etc. */
    }
}

This is a really bad way of null checking. Line 2 wont event execute when null occurs.

The answer by StackFlowed is better.

try {
    for (AnyObject anyObject : anyObjectList) {
        System.out.println(anyObject.doSomething());
    }
} catch (NullPointerException npe){
        // Do your logging here !
}

But we may have to skip the null and get other values. So I found a solution. The code must be like this:

for (AnyObject anyObject : checkIsEmpty(anyObjectList)) {
        System.out.println(anyObject.doSomething());
}

private <T> Iterable<T> checkIsEmpty(Iterable<T> iterable) {
        return iterable == null ? Collections.<T>emptyList() : iterable;
}

Upvotes: 0

StackFlowed
StackFlowed

Reputation: 6816

If you don't want null in your list then most Queue implementations (with the notable exception of LinkedList) don't accept null.

Or you can also use Constraints:

import com.google.common.collect.Constraints;
...
Constraints.constrainedList(new ArrayList(), Constraints.notNull())

from Guava for maximum flexibility.


A better way of doing what you have would be

try {
    for (AnyObject anyObject : anyObjectList) {
        System.out.println(anyObject.doSomething());
    }
} catch (NullPointerException npe){
        // Do your logging here !
}

Upvotes: 0

arshajii
arshajii

Reputation: 129517

Actually you'd often want to know if there is a random null in your list when there shouldn't be. Your first snippet will throw an exception indicating the problem, but your second will consume the error silently.

You could also do something like this:

for (AnyObject anyObject : anyObjectList) {
    if (anyObject != null) {
        System.out.println(anyObject.doSomething());
    } else {
        /* something went wrong -- report error, debugging info, etc. */
    }
}

Upvotes: 4

Related Questions