In my code I usually use this approach to avoid NullPointerException
s 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With