C # lists: initialize with size, why then you can’t use [] access until .Add ()?

This works fine with an array:

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

But this raises an ArgumentOutOfRangeException with a list:

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

Why? I thought that lists use arrays inside.

+4
source share
3 answers

You initialize the capacity, not the size. The score will be zero. Initializing capacity allows you to optimize the size of the internal data structure (array) when you know the maximum size when creating a list. This allows you to save the internal array in a known size and prevents the repeated size of the internal array when adding a known number of elements.

+21
source

new List<int>(10) creates a new list with an 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
source

If you do not specify a capacity, your collection will be redistributed several times, even if it grows to have 100 items. This causes your list to linger twice.

refer to this test page

+1
source

Source: https://habr.com/ru/post/1336184/


All Articles