What's meant by parameter (int initialCapacity)
in an ArrayList
, I thought it's the number of elements but it didn't work when I did this:
public class MyClass { private ArrayList<Integer> arr; public MyClass(int n_elements) { arr = new ArrayList<Integer>(n_elements); } }
An ArrayList has an initial capacity which is simply the size of the array used to store the elements in the list. When you create an ArrayList you can specify the initial capacity. For example: ArrayList<Integer> arrayList = new ArrayList<>(100); In this case, the initial capacity of the ArrayList will be 100.
Best practices in creating ArrayListThe load factor is the measure that decides when to increase the capacity of the ArrayList. The default load factor of an ArrayList is 0.75f. For example, current capacity is 10. So, loadfactor = 10*0.75=7 while adding the 7th element array size will increase.
In the JDK 1.7 into the ArrayList. java the method ensureCapacity increments the array capacity using the following expression: int newCapacity = oldCapacity + (oldCapacity >> 1) so it seems that the new capacity will be almost the 50% more than the old.
It's the initial capacity, i.e. the number of items that ArrayList
will allocate to begin with as the internal storage of items.
ArrayList
can contain "any number of items" (as long you have the memory for it) and when doing large initial insertions you can tell ArrayList
to allocate a larger storage to begin with as to not waste CPU cycles when it tries to allocate more space for the next item.
Example:
ArrayList list = new ArrayList<Integer>(2); list.add(1); // size() == 1 list.add(2); // size() == 2, list is "filled" list.add(3); // size() == 3, list is expanded to make room for the third element
Practically speaking, it's how many elements you can add to the ArrayList
before it resizes in the background, which can save you some cycles if used correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With