Is there a way to avoid null check before the for-each loop iteration starts? [duplicate]
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))
public <T extends Iterable> T nullGuard(T item) {
if (item == null) {
return Collections.EmptyList;
} else {
return item;
}
}
or, if saving lines of text is a priority (it shouldn't be)
public <T extends Iterable> T nullGuard(T item) {
return (item == null) ? Collections.EmptyList : item;
}
would allow you to write
for (Object obj : nullGuard(list)) {
...
}
Of course, this really just moves the complexity elsewhere.