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) {
For anyone uninterested in writing their own static null safety method you can use: commons-lang's org.apache.commons.lang.ObjectUtils.defaultIfNull(Object, Object)
. For example:
for (final String item :
(List)ObjectUtils.defaultIfNull(items, Collections.emptyList())) { ... }
ObjectUtils.defaultIfNull JavaDoc