Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's meant by parameter (int initial capacity) in an arraylist

Tags:

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);     } } 
like image 821
Ismail Marmoush Avatar asked Nov 13 '10 12:11

Ismail Marmoush


People also ask

What is initial capacity in ArrayList?

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.

What is load factor and initial capacity in ArrayList?

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.

How do you calculate capacity of an ArrayList?

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.


2 Answers

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 
like image 155
Patrick Avatar answered Sep 20 '22 22:09

Patrick


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.

like image 41
Carl Avatar answered Sep 20 '22 22:09

Carl