Null check in an enhanced for loop

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

    With Java 8 Optional:

    for (Object object : Optional.ofNullable(someList).orElse(Collections.emptyList())) {
        // do whatever
    }
    

提交回复
热议问题