开发者

Does the List in .NET work the same way as arraylist in Java?

When I learned Java, I was told that the arraylist works this way:

  • It creates an array with room for 10 elements.

  • Wh开发者_如何学Pythonen the 11th element is added, it is created a new list with room for 20 elements, and the 10 elements are copied into the new array. This will repeat as until there are no more elements to add, or to a maximum size.

Is the List in .NET constructed the same way?


You can easily test this by querying a List's Capacity:

    var a = new List<string>();

    Console.WriteLine(a.Capacity); // Writes 0

    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 4

    a.Add("abc");
    a.Add("abc");
    a.Add("abc");
    a.Add("abc");

    Console.WriteLine(a.Capacity); // Writes 8

So it doesn't allocate any room at all upon instantiation, but upon first added item. From 8 it grows to 16, 32, etc...


The generic List type doubles its internal array length every time the current array is filled up.

MSDN Link


The details are a bit different (in terms of the default number of elements and how it expands), but essentially it is the same.


I believe that's how it works, yes. I can't find any documentation at the moment that tells you the exact algorithm they use, but there is definitely the concept of Capacity (size of the "internal" array) and Count (the actual number of elements you've added).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜