When you create a collection object (List, Set, etc), usually they take a parameter known as "initialCapacity". What does this parameter mean and how is it used ?
views:
362answers:
5If you add lots of elements to the collection, the backing array needs to 'grow' frequenty. Setting the capacity might avoid this frequent array reallocation and data copy along with the pressure for the GC.
For example if you suspect your list will contain about 1000 elements, instantiate this way:
new ArrayList(1000);
Its the size allocated for your array initially. The list can grow of course, but when it does it needs to allocate more space. So giving it an initial capacity is a performance consideration.
It specifies how large to initialize the underlying array/base collection that it is encapsulating. If you know that your data structure is going to be of approximate size X when you initialize it, you can save some CPU cycles later on since the class will not have to dynamically resize it self (as often) while you add items to the collection.
Resizing a dynamic data structure is a potentially costly operation. All Java Collections have a default size and grow as necessary. If you know when you create a data structure that the size will exceed the default, then you can avoid some of the resizing that Java would do behind the scenes by setting the initial capacity to a value close to but in excess of the expected size.
Javadoc for each of the collections describes the default initial capacity. You should be especially aware of HashMaps since resizing also means rehashing all of the keys in the map.