开发者

C# Lists: initialize with size, why then can't use [] access until after .Add()?

This works fine with an array:

int[] a = new int[10];
for (int i = 0; i < 10; i++)
{
    a[i] = i;
}

But this throws an ArgumentOutOfRangeExce开发者_Go百科ption with a list:

List<int> a = new List<int>(10);
for (int i = 0; i < 10; i++)
{
    a[i] = i;
}

Why is that? I thought that lists used arrays internally.


You are initializing the capacity, not the size. The count will still be zero. Initializing the capacity allows an optimization to size the internal data structure (an array) when you know the maximum size when creating the list. This keeps the internal array to a known size and prevents internal array re-sizing as you add the known number of elements.


new List<int>(10) creates a new list with the initial capacity of 10 items. The list is still empty.

You need to add items to it before you can access them by index.


When you don't specify a capacity, your collection will be reallocated several times if it even grows to have 100 elements. This makes populating your list twice as slow.

refer to this test page

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜