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.
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))