null-safe Collection contains method

wrschneider picture wrschneider · Dec 12, 2012 · Viewed 12.1k times · Source

What's the best way to do null-safe contains on a Java collection?

in other words -

 if (collection != null && collection.contains(x))

?

I was hoping Apache commons-collections had something like CollectionUtils.contains(collection, x) that would simply return false if the collection was null, as there is with size(), which treats null like an empty collection.

However, it seems like there is no such thing - did I just miss it?

Answer

Thorn G picture Thorn G · Dec 12, 2012

You should instead be applying the Null Object Pattern here and use an empty collection, rather than a null collection. Of course, perhaps this is appropriate for your problem, but without more context it's hard to tell. In other words, I think you are solving the wrong problem -- why might collection be null in the first place?