Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Capacity of List

What is the default capacity of a List?

like image 806
Jawahar BABU Avatar asked Nov 19 '09 11:11

Jawahar BABU


People also ask

What is the capacity of list?

Capacity is the number of the elements which the List can store before resizing of List needed. But Count is the number of the elements which are actually present in the List.

What's default capacity in ArrayList source code?

The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain. The default capacity is 4. If 5 elements are there, then its capacity is doubled and would be 8.

How big can a list be in C#?

List size can be increased up to 2 billion (only when your system works on 64-bit or higher) to store large List<T> objects.

What is default vector capacity?

Default initial capacity of Vector is 10. java. util. Vector default constructor defines size of 10.


2 Answers

Actually, it starts with a Capacity of 0. When you add the first element, the current implementation allocates a capacity of 4. After that, the capacity keeps doubling if expansion is needed, to guarantee amortized O(1) operation.

Keep in mind that this is the current behavior. You shouldn't rely on it to be the case. This should demonstrate the current behavior:

List<int> list = new List<int>();
int capacity = list.Capacity;
Console.WriteLine("Capacity: " + capacity);

for (int i = 0; i < 100000; i++)
{
    list.Add(i);
    if (list.Capacity > capacity)
    {
        capacity = list.Capacity;
        Console.WriteLine("Capacity: " + capacity);
    }
}
like image 79
Thorarin Avatar answered Oct 09 '22 03:10

Thorarin


Why don't you just try it?

Console.WriteLine("Default capacity of a List: " + new List<int>().Capacity);

This answer will work on all versions of .NET that have List. On my version, it happens to be 0.

like image 60
Mark Byers Avatar answered Oct 09 '22 05:10

Mark Byers