C# Lists: initialize with size, why then can't

2020-04-08 14:02发布

问题:

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 ArgumentOutOfRangeException 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.

回答1:

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.



回答2:

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.



回答3:

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



标签: c# arrays list