Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Null Pointer Exception in "for" statement

In my code I usually use this approach to avoid NullPointerExceptions in for statements when a List is null:

if (myList != null && myList.size() > 0) {
    for ( MyObj obj : myList ) {
        System.out.println("MyObjStr: "+obj);
    }
}

Is there another way to do the same without write the "if" statement, but using the same "for" statement?

like image 434
fl4l Avatar asked Apr 08 '14 09:04

fl4l


1 Answers

The check for the size is not needed. Your for-loop will not execute if is there are no objects in the list.

The check for null is only needed, when you are not sure about the object's state. But when using your own objects (nothing given from outside via arguements e.g.) then there is no need for the null check.

See Avoiding “!= null” statements in Java? for a brilliant explanation why unexperienced developers often exaggregate with null checks.

like image 51
ifloop Avatar answered Oct 19 '22 09:10

ifloop