I have some classes that have ArrayList
fields that are only sometimes used. I generally initialize these fields like so:
private List<Widget> widgets = new ArrayList<>();
I understand about using the overload constructors to set the initial capacity, so I'm wondering if I should declare these fields as such:
private List<Widget> widgets = new ArrayList<>(0);
The dilemma, is that if I initialize the list with 0 then the list will always have to re-initialize itself for adding even one item. But, if I use the default constructor, which gives a default capacity of 10, then I may have a bunch of items (and there can be many) that are wasting memory with unused capacity.
I know some of you are going to push back asking 'how often' and 'how many items are you expecting' but I'm really looking for the "best practices" approach. All things being ~equal, should one initialize with (0)
or ()
on a list that is sometimes used?
It's our department policy to always initialize lists, so I may not simply leave the lists as null
, besides, that would just side-step the question.