If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following \"idiom\" in order to save unnecessary object crea
in order to save unnecessary object creations
That's a really bad idea which will litter your code with == null
checks and other handling of corner cases (and presumably end up in null pointer exceptions anyway)!
Now I was wondering if I couldn't eliminate those null checks using
Collections.emptyList()
No, not really. emptyList()
returns an empty list. You could do
if (list.equals(Collections.
but that will still throw a NullPointerException if list == null
, so it's still not what you're after.
My recommendation: Always initialize the list to new ArrayList
, or, if you for instance want to return an empty list from a method, use Collections.emptyList()
instead. (This returns the same instance every time, so no unnecessary object creation there either.)
And then use .isEmpty()
to check if a collection is empty or not.