Null check in an enhanced for loop

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

    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.

提交回复
热议问题