Null check in an enhanced for loop

前端 未结 11 1957
南旧
南旧 2020-11-29 15:35

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


        
11条回答
  •  一生所求
    2020-11-29 16:15

    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

提交回复
热议问题