Number of times we have check condition like whether list is null or not.
For a start, a null
collection and an empty collection are different things. If you need to test if a collection is null
you need a different test to if you are trying to test if the collection is empty.
Secondly, if a collection could be either null
or empty (and they "mean" the same thing, per your application design) then you have a problem in your design. You should most likely represent ... whatever it is you are trying to represent ... one way, and not either / both ways.
Thirdly, it is generally best to use an empty collection rather than a null
, because you can treat an empty and non-empty collection uniformly. By contrast, a null
always needs to be handled as a special case. (And if you forget to handle the null
case, then you've got a potential for NullPointerExceptions
.)
Having said that ...
Which is best condition or do we need to make some combination of these considering performance of program execution?
If you really need to deal with the case of a null
, then you've no choice but to test for null
.
For isEmpty()
versus size() == 0
:
the two predicates should give the same answer (unless you have an infinite lazy collection ...), but
in some cases isEmpty()
could be faster, at least in theory.
The latter depends on the implementation of the collection type: specifically, on whether the size()
method needs to count the collection elements. (I don't think that any of the standard collection classes have this property, but that's not to say that you won't find some class that does ...)
So the optimal predicate is most likely either:
c != null && !c.isEmpty()
or
!c.isEmpty()
depending on whether you (really) need to cater for nulls.
And the obvious corollary is that your application is likely to be more efficient ... as well as simpler and more robust ... if you don't use null
to represent empty collections. (If you need immutable empty collection objects, you can get them for free from methods / statics defined by the Collections
class.)