Null check in an enhanced for loop

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

    You should better verify where you get that list from.

    An empty list is all you need, because an empty list won't fail.

    If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:

    for( Object o : safe( list ) ) {
       // do whatever 
     }
    

    And of course safe would be:

    public static List safe( List other ) {
        return other == null ? Collections.EMPTY_LIST : other;
    }
    

提交回复
热议问题