Null check in an enhanced for loop

前端 未结 11 1953
南旧
南旧 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:27

    Use, CollectionUtils.isEmpty(Collection coll) method which is Null-safe check if the specified collection is empty.

    for this import org.apache.commons.collections.CollectionUtils.

    Maven dependency

    
        org.apache.commons
        commons-collections4
        4.0
    
    

提交回复
热议问题