Null check in an enhanced for loop

前端 未结 11 1959
南旧
南旧 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

    If you are getting that List from a method call that you implement, then don't return null, return an empty List.

    If you can't change the implementation then you are stuck with the null check. If it should't be null, then throw an exception.

    I would not go for the helper method that returns an empty list because it may be useful some times but then you would get used to call it in every loop you make possibly hiding some bugs.

提交回复
热议问题