Null check in an enhanced for loop
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) {
// 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?
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:
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:
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.
It's already 2017, and you can now use 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
.
With Java 8 Optional
:
for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
// do whatever
}