Is there a way to avoid null check before the for-each loop iteration starts?

rk2010 picture rk2010 · May 20, 2011 · Viewed 126.9k times · Source

Every time I have to iterate over a collection I end up checking for null, just before the iteration of the for-each loop starts. Like this:

if( list1 != null ){
    for(Object obj : list1){

    }
}

Is there a shorter way, so that we can avoid writing the "if" block ? Note: I am using Java 5, and will be stuck with it for sometime.

Answer

SLaks picture SLaks · May 20, 2011

If possible, you should design your code such that the collections aren't null in the first place.

null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList())

Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable<T>(list1))