hi today stumbled on thing list<t>(int32)
. thought behaviour same in following examples:
1.
var mylist = new list<string>(5); mylist[1] = string.empty;
2.
var myarray= new string[5]; myarray[1] = string.empty;
the first example fails , 'system.argumentoutofrangeexception'. second example works well.
so tried .count
on list , says 0, when put .length
@ array says 5.
in msdn says:
initializes new instance of list class empty , has specified initial capacity.
i thought means list has initial size pass in. why isn't case?
thanks in advance!
the initial capacity refers internal array storage maintained list.
if expect hold 100 items , specify 100 initial capacity, avoid overhead of internal resizing of array (well, list avoids creating new array , copy values previous one...).
maybe you've realized list (and many other collection types) abstraction of arrays provide specific semantics: lists, sets, dictionaries...
for example, list collection 100
items of initial capacity might add items internal array has 100
indexes/slots:
int[] array1 = new int[100]; array1[0] = 1; // until... array1[99] = 2;
...while 1 doesn't provide good capacity, may need internally handle insertion of 100 items way:
int[] array2 = new int[3]; array2[0] = 1; array2[1] = 2; array2[2] = 3; int[] array3 = new int[6]; array2.copyto(array3); array3[3] = 4; array3[4] = 5; array3[5] = 6; int[] array4 = new int[9]; array3.copyto(array4); array4[6] = 7; array4[7] = 8; array4[8] = 9; // , on...
the whole internal array list's storage minimum reservation, implementation detail. if know how many items you're going add list, it'll better provide initial capacity.
note initial capacity doesn't fix maximum capacity of whole list. defeat purpose , semantics of lists: collection of objects ordered inserting order (fifo, first-in, first-out). once capacity has been reached, internal array resized again.
also, since lists in higher-level described object collections, can't expect providing initial capacity provide access internal storage indexes. fact there's internal array storing collection's object implementation detail, need rely on high-level details:
// above reason why can't access mylist[1] var mylist = new list<string>(5); mylist[1] = string.empty;
further details
hopefully, .net framework source code available online. can take @ list<t>
source code check how works internally:
Comments
Post a Comment