What is the initial size of ArrayList in C#?
I want t开发者_如何学Pythono know what is the initial size of ArrayList in C#?
0
. See below.
16
. (I have to add characters to this answer, since 18 characters are minimum)
Edit, Oops - the initial capacity is 16. Initial size is of course 0, because it's empty. Have to learn how to read. Or you have to learn how to form your questions. ;)
Edit again; Initial capacity of an ArrayList in .NET 1.0 is 16. In 2.0 it was 4, and now - with .NET 3.5 - the initial capacty has been lowered to 0. I don't have an explanation of why, thou.
When adding a first element to the list, the capacity will be set to 4. There after, every time when arraylist.Count eq arraylist.Capacity, the capacity will double.
The ArrayList starts with Size = 0 (because it's empty) and Capacity = 16.
The capacity is doubled as necessary, and capacity-doubling is a O(n) operation where n is the new capacity. So if you're inserting 5,000 elements into your list, the framework's going to be doubling the ArrayList capacity nine times - and each doubling operation is twice as expensive as the previous one.
In other words - if you know you're going to be putting 5,000 elements in a list, you're much better off explicitly initializing it to hold 5,000 elements.
You can explicitly set the Capacity of an existing arraylist if you know you're about to insert a large number of elements. You can also decrease Capacity explicitly, but if you set Capacity < Count, you'll get an ArgumentOutOfRange exception.
NOTE: The following seemingly only holds true for .NET 3.5; in previous versions of the framework the values were different.
According to my tests here both the initial size and capacity are zero:
PS> $a = new-object system.collections.arrayList
PS> $a.Capacity
0
PS> $a.count
0
Also, looking at the source code in Reflector, the same holds true:
public virtual int Capacity
{
get
{
return this._items.Length;
}
...
}
And _items
gets set to an empty object[]
in the ctor.
The ArrayList is empty when you have created it, so the size is zero.
Unless you are stuck with framework 1, you should not use the ArrayList
class at all. Use the strongly typed generic List<T>
class instead.
ArrayList list = new ArrayList();
size = 0 before adding items to the arrayList, means no items are there.
Try yourself.
int capacity = (new ArrayList()).Capacity;
should give you the initial capacity.
精彩评论