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 creations:
List<Object> list = null;
void add(Object object) {
if (list == null)
list = new ArrayList<Object>();
list.add(object);
}
// somewhere else
if (list != null)
for (Object object : list)
;
Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList()
, however then I would have to alter the if check in add()
like so:
if (list == Collections.<Object>emptyList())
list = new ArrayList<Object>();
Is there a better way to handle this other than just allocating a new empty collection every time?
EDIT: just to be clear, I would like to use Collections.emptyList(), but the above check in add() is really really ugly... I was wondering if there's a better way to do it or even a whole other way of handling this.
emptyList() doesn't allocate an object each time.
I would create less of the object which contains the List so you can create the list every time.
What you can do is
Here's a variation on using optional as @Stas suggested, but also using the isEmpty immutable collection as originally requested in the question:
This approach is also the closest thing I can find to the nice ability in Javascript to use an empty array if the collection is null.
For example: