Null check in an enhanced for loop

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

    You could potentially write a helper method which returned an empty sequence if you passed in null:

    public static  Iterable emptyIfNull(Iterable iterable) {
        return iterable == null ? Collections.emptyList() : iterable;
    }
    

    Then use:

    for (Object object : emptyIfNull(someList)) {
    }
    

    I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.

提交回复
热议问题